int SumBetween(int low, int high)
{
int i;
int end;
int Ray[high - low];
int sum;
end = (high - low);
for (i = 1; i = end; i++) {
Ray[i] = low + i;
}
sum = 0;
for (i = 1; i = end; i++) {
sum = sum + Ray[i];
}
return sum;
}
上述功能不断出现此错误:
main.c: In function 'SumBetween':
main.c:12:2: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
for (i = 1; i = end; i++) {
^
main.c:17:2: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
for (i = 1; i = end; i++) {
^
cc1: all warnings being treated as errors
我做错了什么?
答案 0 :(得分:2)
您的问题在技术上不是错误,而是警告。在您的情况下,所有警告都表示为错误,因为编译器在您的代码中检测到可能的问题。
如您所见,您的for循环中存在问题:
i = 0
,因为数组以C中的0
开头根据您的代码,您应该将for循环重写为
//Start with i = 0 and go till end variable
// 1 2 3
for (i = 0; i < end; i++) {
Ray[i] = low + i;
}
答案 1 :(得分:0)
从技术上讲,如果end! = 0
,你的()语句就是无限循环。
假设high
大于low
(或值相等),您可以通过执行以下操作来避免第二个循环:
int SumBetween(int low, int high)
{
int i, end, sum = 0;
end = (high - low);
for (i = 1; i != end; i++) {
sum += low + i;
}
return sum;
}
顺便说一句,我的建议依赖于您需要从end
i = 1
值的假设