桁の和の計算

CCBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C プログラミング言語を使って、与えられた数の桁の和を計算するプログラムを書く方法を学びます。

注: コーディングを練習し、gcc を使ってコンパイルと実行方法を学ぶために、~/project/main.c ファイルを自分で作成する必要があります。

cd ~/project
## main.c を作成する
touch main.c
## main.c をコンパイルする
gcc main.c -o main
## main を実行する
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c/BasicsGroup -.-> c/variables("Variables") c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/while_loop("While Loop") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123338{{"桁の和の計算"}} c/operators -.-> lab-123338{{"桁の和の計算"}} c/while_loop -.-> lab-123338{{"桁の和の計算"}} c/user_input -.-> lab-123338{{"桁の和の計算"}} c/output -.-> lab-123338{{"桁の和の計算"}} end

変数を定義してユーザーから入力を受け取る

このステップでは、3 つの変数 nsum、および remainder を定義します。scanf() 関数を使って、変数 n にユーザーからの入力を受け取ります。

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    // 桁の和のコード

    return 0;
}

桁の和を計算する

このステップでは、与えられた数の桁の和を計算するために while ループを使います。

while(n!= 0)
{
    remainder = n % 10;
    sum += remainder;
    n = n / 10;
}

上記のコードは、剰余演算子 (%) を使って、数を 10 で割ったときの余りを取得します。この余りを変数 sum に加算します。その後、数を 10 で割って、その数の最後の桁を取り除きます。このプロセスを数が 0 になるまで繰り返します。

合計を表示する

このステップでは、printf() 関数を使って、上で計算した桁の和をユーザーに表示します。

printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
printf("\n\n\n\n\t\t\tCoding is Fun!\n\n\n");

完全なプログラムを書く

ここでは、上記のすべてのステップをまとめて、数の桁の和を計算する完全なプログラムを書きます。

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    while(n!= 0)
    {
        remainder = n % 10;
        sum += remainder;
        n = n / 10;
    }

    printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
    printf("\n\n\n\n\t\t\tCoding is Fun!\n\n\n");

    return 0;
}

まとめ

この実験では、C プログラミング言語を使って与えられた数の桁の和を計算するプログラムを書く方法を学びました。剰余演算子と while ループを使って和を計算しました。