How to calculate the sum of multiple numbers in the C l…

In the C language, you can use loop structures to calculate the sum of multiple numbers.

Here is an example code for calculating the sum of multiple numbers:

#include <stdio.h>

int main() {
    int num;       // 存储输入的数字
    int sum = 0;   // 存储和的变量
    int count;     // 计数变量,用来统计输入了多少个数字

    printf("请输入数字的个数:");
    scanf("%d", &count);

    printf("请输入%d个数字:\n", count);
    for (int i = 0; i < count; i++) {
        scanf("%d", &num);
        sum += num;   // 将输入的数字累加到sum变量上
    }

    printf("这%d个数字的和为:%d\n", count, sum);
    
    return 0;
}

This program first asks the user to input the number of digits, then uses a loop to read the user’s input numbers and adds them to a sum variable. Finally, it prints out the sum of these numbers.

When the program is running, it will prompt you to input the number of digits, then enter the corresponding number of digits, and finally output the sum of these numbers.

bannerAds