c - 如何计算递增变量的总计

标签 c variables math

如果有一个名为a的变量,它不断地向上计数,但是当达到某个数字时又重置为0,我该如何计算该变量的总数?例如:

    int count = 0;
    int a = 0;
    int total = 0;
    while (true) {
         count++;
         a = count % 1000;
         total = ...;
    }

其中“total”是a的总值,它会超过1000。简单地添加它是行不通的,因为它会变成total+=1、total+=2、total+=3等等。怎么办?我每次循环都计算这个?谢谢你的帮助。 :) 顺便说一句,我正在使用 C,尽管这并不重要。

最佳答案

这应该可行。在您的程序中,totala 的值没有任何关系。

           int count = 1;
            int a = 0;
            int total = 0;
            while ((count+1001)%1001) {                     
                 a = (count+1001) % 1001;
                 count++;
                 total = total+a;
            }
           printf("The sum of 1000 numbers is %d",

          total);

关于c - 如何计算递增变量的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334101/

相关文章:

C 宏 - 动态#include

c - C中的副作用是什么?

c - 是什么导致此 for 循环中的内存泄漏?

php - 将 url 变量传递到下一页?

Javascript - event.clientX 和 style.left - 数学运算

javascript - 在时间轴上定位条目

检查字符串是否是字谜

r - 如何使用字符作为函数的属性

javascript - 如何在 JavaScript 中引用表示变量?

python - 用于打印数字除数乘积的高效 python 代码