因此,我正在编写一个有关查找所有范围的总和的程序,例如,如果我输入1,然后输入10,它应该显示55,但是显示一些长的随机数。有人知道此代码有什么问题吗?谢谢!
#define <stdio.h>
calculateSum(int lowNumber, int highNumber);
int main()
{
int lowerNumber,
higherNumber;
scanf("%d", lowerNumber);
scanf("%d", higherNumber);
printf("The sum of all ranges is: %d", calculateSum(lowerNumber, higherNumber));
int calculateSum(int lowNumber, int highNumber)
{
int total;
for(int x = lowNumber; x <= highNumber; x++)
{
total = total + x;
}
return total;
}
答案 0 :(得分:1)
在BarConsumerFactory
首次用作右值(赋值myTextField.SendActionForControlEvents(UIControlEvent.EditingChanged);
的RHS)之前,您不需要进行初始化,因此其值仍不确定(且不确定)。
答案 1 :(得分:1)
除了@biplls answer之外,还有另一个问题:
int lowerNumber,
higherNumber;
scanf("%d", lowerNumber);
scanf("%d", higherNumber);
是UB(在运行时生成有关编译的警告和SEGFAULT)。 printf
期望int*
,而不是int
。正确的代码是
int lowerNumber,
higherNumber;
scanf("%d", &lowerNumber);
scanf("%d", &higherNumber);
答案 2 :(得分:1)
这里有一些错误
#include <stdio.h>
而不是#define
scanf
时,您必须在读入的var之前添加一个&
(在这种情况下!)total
应该设置为0 解决所有问题
#include <stdio.h>
int calculateSum(int lowNumber, int highNumber);
int main()
{
int lowerNumber,
higherNumber;
scanf("%d", &lowerNumber);
scanf("%d", &higherNumber);
printf("The sum of all ranges is: %d\n", calculateSum(lowerNumber, higherNumber));
return 0;
}
int calculateSum(int lowNumber, int highNumber)
{
int total;
total = 0;
for(int x = lowNumber; x <= highNumber; x++)
{
total = total + x;
}
return total;
}
运行以上
$ ./sum
1
10
The sum of all ranges is: 55