【发布时间】:2019-05-03 01:34:17
【问题描述】:
我是 C 编程语言的新手。我试图在 N 次以下运行代码(基于“输入迭代次数”的用户输入)。我正在尝试使用 for 循环(也尝试使用 while 循环)来执行此操作,但没有成功。
每当我运行下面的代码时,我的终端都会不断重复“输入两个浮点数:”。我必须关闭终端并重新打开它才能重试。这个问题与我的 for 循环有关吗?我将我的 for 循环解释为:“a=0;如果 a > 0;递增 a”。有没有办法可以为“if a > 0”设置限制,或者我应该使用 while 循环?如果用户输入“3”作为迭代次数,我希望程序会询问“输入两个浮点数”3 次(带有答案)。
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
正确答案为便于阅读而格式化:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
【问题讨论】:
-
你有很奇怪的
for循环:for (int a; a > 0; a++),可能是这样写的for (int i = 0; i < a; i++)? -
请不要在 C 中使用 Pico 样式的缩进;它非常不正统,几乎无法阅读。此外,白色空间很便宜;用它!请使用 Allman(我喜欢的风格)或 1TBS(很多其他人喜欢它)——有关更多信息,请参阅 Wikipedia on Indentation Styles。
-
此外,
printf有一个缓冲区用于临时存储您的打印数据,直到它没有足够的填充,您可以在printf之后使用fflush(stdout)以避免缓冲您的输出。 -
请注意,
for循环中的a与前面代码中声明并由输入操作设置的a不同且无关。for循环中的a没有初始化;您无法确定循环将执行多少次。一个好的编译器应该警告你重新定义或隐藏a。 -
谢谢你,J.S!工作完美..第一天学习C。谢谢大家的指导。我将不再在 c 中使用 Pico 样式的缩进! :D
标签: c loops for-loop while-loop