![](/img/trans.png)
[英]C Socket program - How can I accept user input while updating reading from stdout?
[英]How can I get this C program to accept new input without adding it to the old input?
我不得不参加编程练习,我必须做好功课。 我已经非常接近完成它,但我无法弄清楚如何让程序在最后没有程序将新输入添加到旧输入时要求用户“输入下一组限制”。
这是我书中出现的问题:
编写一个请求下限和上限整数的程序,计算从下限的平方到上限的平方的所有整数的平方和,并显示答案。 然后,程序应继续提示限制并显示答案,直到用户输入等于或小于下限的上限。 示例运行应如下所示:
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;
}
我真的很讨厌你for
循环。 但那是暂时的。
只需在循环中将total
设置为零......无论如何你应该这样做。 目前它没有被初始化。
您应该在lower == upper
时退出循环而不进行计算。 请参阅前面有关您的for
循环的说明。
也许是这样的:
printf("Enter lower and upper integer limits: ");
fflush(stdout);
while ( 2 == scanf("%d %d", &lower, &upper) && lower < upper )
{
total = 0;
// Do calculation and output result...
printf("Enter the next set of limits: ");
fflush(stdout);
}
printf("Done\n");
int index, lower, upper, square, total, input;
while(1)
{
total = 0;
printf("Enter lower and upper integer limits: ");
fflush(stdout);
input = scanf("%d %d", &lower, &upper);
if(input != 2) continue;
if(upper <= lower) break;
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 , upper, total );
}
printf("Done\n");
只需将代码包装在:
while( upper > lower ) {
...
}
(并适当地初始化upper
和lower
以便输入循环。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.