简体   繁体   English

如何使用C语言显示用户的5个输入数字的总和

[英]how to display the sum of 5 input numbers from user using c language

#include <stdio.h>
#include <conio.h>

main() {
    float num1, num2, num3, num4, num5, sum;

    printf("Enter a Number between");
    fflush;
    scanf("%f",&num1);
    fflush;

    printf("Enter a Number between");
    scanf("%f",&num2);
    fflush;

    printf("Enter a Number between");
    scanf("%f",&num3);
    fflush;

    printf("Enter a Number between");
    scanf("%f",&num4);
    fflush;

    printf("Enter a Number between");
    scanf("%f",&num5);
    fflush;

    sum = num1 + num2 + num3 + num4 + num5;
    printf("The sum of the five numbers you have entered is %f",sum);

    getch();
}

I am a newbie in c programming. 我是C编程的新手。 We have an assignment and I have created the above code. 我们有一个作业,我已经创建了上面的代码。 But we need a shorter solution. 但是我们需要一个更短的解决方案。 The user must input five numbers and display the sum. 用户必须输入五个数字并显示总和。 Can you please help me to translate this code using do while function or post test loop. 您能帮我使用do while函数或测试后循环翻译此代码吗? Thank you very much in advance! 提前非常感谢您!

You can use a cycle to read 5 values and accumulate their sum. 您可以使用一个循环读取5个值并累加它们的总和。 I prefer to leave you with this hint only because this seems like a homework assignment. 我只想给您这个提示,因为这似乎是一项家庭作业。 You may reuse the same variable reading 5 different inputs and have a separate variable in which you accumalate the sum. 您可以重复使用相同的变量来读取5个不同的输入,并拥有一个用于累积总和的单独变量。 You can also use a for cycle instead of the do... while you seem to be using. 您似乎可以使用时,也可以使用for循环而不是do... while

Use a for loop to input numbers (say 5 in this case) and add it with value stored in sum in each iteration. 使用for循环输入数字(在这种情况下为5 ),并将其与每次迭代中存储的sum

     int num , sum = 0;  

     for(int i = 0; i < 5; i++)
     {
         scanf("%d", &num);  
         sum += num;
     }

When someone asks me to do their homework for them, I enjoy coming up with a slightly convoluted, but functionally correct answer. 当有人要我为他们做功课时,我很喜欢提出一个有点复杂但在功能上正确的答案。 :) :)

#include <stdio.h>
#include <conio.h>

int main()
{
    float numbers[5] = {0.0F};
    float sum = 0.0F;
    int count = 5;

    while(count --> 0)
    {
        printf("Enter a number for entry %d: ", 5-count);
        scanf("%f",numbers+count);
        sum += numbers[count];
    }
    printf("The sum is %f\n", sum);
    getch();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM