C 程序 - 将 while 循环中的整数相加

标签 c console

我正在尝试创建一个简单的 C 程序,它将不断要求用户输入一个数字,直到输入负数,然后当输入负数时,它将添加用户输入的所有正数。我遇到了问题,因为我根本不知道如何将输入的数字相加。我已经开始并到目前为止:

  int main()
    {
       int numbersEntered, sum;
       while(numbersEntered>0) {
       printf("Enter Numbers to add together: ");
       scanf("%d", &numbersEntered);
       }
       printf("%d", sum);
    }

我不知道如何计算输入的所有整数的总和。

最佳答案

程序可以如下所示

#include <stdio.h>

int main( void )
{
    int numberEntered;
    long long int sum;

    sum = 0;

    printf( "Enter numbers to add together (a negative number - exit): " );

    while( scanf( "%d", &numberEntered ) == 1 && numberEntered >= 0 ) 
    {
        sum += numberEntered;
    }

    printf( "%lld\n", sum );
}

关于C 程序 - 将 while 循环中的整数相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36373026/

相关文章:

c - 如何将 4 个 modbus 寄存器(每个 16 位)转换为 C 中的双 float ?

c - 如何将 C 函数移动到单独的文件中?

c# - 我应该如何用科学记数法(+301)解析一个非常大的数字?

perl - 读取 Perl 中 shell 脚本的控制台输出

c - 在 gcc 中使用数学函数时出错?

无法理解此代码堆栈存储函数调用 c 的输出

c - 编程查找总和,如果输入 'y',则使用 do while 循环重复该过程

支持全键盘的 Linux 终端?

javascript - 如何忽略 Google Chrome Javascript 控制台中的重复条目(在 Web 开发人员工具中)?

Linux shell (Bash/Z shell) - 在特定目录下更改背景颜色