我需要知道如何在循环中获得变量中存在的数字总和,我有这样的代码:
int starting = 3
int ending = 6;
int factor1 = 3;
do {
int y = starting * factor1;
int sum = 0;
int all = sum += y;
Console.WriteLine("value of a: {0}", all);
starting = starting + 1;
} while (starting < ending);
我需要代码在数字3 - 6之间进行数字3的乘法运算,然后对所有值求和。像这样的东西:
(3*3)+(3*4)+(3*5)+(3*6) = 9+12+15+18 = 54
答案 0 :(得分:2)
你只需要声明在循环外保持总数的变量,这样你就不会在每次迭代时覆盖它:
int sum = 0;
do
{
sum += starting * factor1;
starting++;
} while (starting <= ending);
您还需要将condidion starting < ending
更改为starting <= ending
,否则循环将在到达最后一个数字时停止(在这种情况下为6)。