我被困在我必须为家庭作业做的编程练习上。我已经非常接近完成它,但我只是不知道如何让程序在最后要求用户“输入下一组限制”,而无需程序将新输入添加到旧输入中。
这是我书中出现的问题:
编写一个请求整数下限和上限的程序,计算从下限平方到上限平方的所有整数平方和,并显示答案。然后程序应继续提示限制并显示答案,直到用户输入等于或小于下限的上限。示例运行应如下所示:
Enter lower and upper integer limits: 5 9 The sums of the squares from 25 to 81 is 255 Enter next set of limits: 3 25 The sums of the squares from 9 to 625 is 5520 Enter next set of limits: 5 5 Done
这是我写的代码:
#include <stdio.h>
int main(void)
{
int index, lower, upper, square, total, input;
printf("Enter lower and upper integer limits: ");
for (input = scanf("%d %d", &lower, &upper); input == 2; printf("Enter the next set of limits: \n"), scanf("%d %d", &lower, &upper))
{
for (index = lower; index <= upper; index++)
{
square = index * index;
total += square;
}
printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, total);
}
return 0;
}
任何帮助将非常感激!我已经为此工作了一个多小时。
更新,这就是我现在所拥有的,但它仍然不正确,因为当上限和下限相同时它不会打印出“完成”:
包括
int main(void) { int index, lower, upper, square, total;
printf("Enter lower and upper integer limits: ");
while (scanf("%d %d", &lower, &upper) == 2)
{
total = 0;
for (index = lower; upper > index; index++)
{
square = index * index;
total += square;
}
printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, total);
printf("Enter the next set of limits: \n");
}
return 0;
}
更新* ****
感谢大家的帮助,我想我终于明白了:
包括
int main(void) { int index, lower, upper, square, total;
printf("Enter lower and upper integer limits: ");
while (scanf("%d %d", &lower, &upper) == 2)
{
while (lower < upper)
{
total = 0;
for (index = lower; index <= upper; index++)
{
square = index * index;
total += square;
}
printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, total);
printf("Enter the next set of limits: \n");
scanf("%d %d", &lower, &upper);
}
printf("Done");
}
return 0;
}