![](/img/trans.png)
[英]Space at the end of input line causes while loop to go one more time than it should
[英]My while loop in C replays one more time than it should before it ends
当给定输入时,我的 while 循环在关闭循环之前额外打印一次。 例如, 8 7 38 3 -5 -1 q 是我打印出来的输入
为强力方程求解器提供 6 个 integer 系数: 找到的解:x = 3, y = 2
再次运行程序? 输入“q”退出或任何其他键继续:
为强力方程求解器提供 6 个 integer 系数: 找到的解:x = 3, y = 2
再次运行程序? 输入“q”退出或任何其他键继续:
第一次迭代后应该何时结束。 谁能帮我解决这个问题? 我的代码粘贴在下面
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int main(void)
{
//Equations should be a1x + b1y = c2 and a2x + b2y = c2
int a1, b1, c1, a2, b2, c2, x, y;
char input;
bool solFound = false;
bool runAgain = true;
//brute force x and y [-10, 10]
while (runAgain == true)
{
printf("Provide 6 integer coefficients for the brute force equation solver: ");
scanf("%d %d %d %d %d %d", &a1, &b1, &c1, &a2, &b2, &c2);
for (x = -10; x<=10; x++)
{
for (y = -10; y<=10; y++)
{
if (a1*x + b1*y == c1 && a2*x + b2*y == c2)
{
printf("\nSolution found: x = %d, y = %d\n\n", x, y);
solFound = true;
runAgain = false;
}
}
}
if (solFound != true)
{
printf("No solution found\n\n");
runAgain = false;
}
scanf("%c", &input);
printf("Run program again? Type 'q' to quit or any other key to continue:");
if (input != 'q')
{
runAgain = true;
}
printf("\n\n");
}
} ```
对于初学者,变量sqlFound
应该在 while 循环中声明,或者至少在 while 循环中重新初始化。 例如
while (runAgain == true)
{
bool solFound = false;
//...
否则它将保留循环的前一次迭代的值。
在这个 if 语句中
if (solFound != true)
{
printf("No solution found\n\n");
runAgain = false;
}
设置变量runAgain
runAgain = false;
没有意义,因为在这个 if 语句之后你再次询问是否重复循环
printf("Run program again? Type 'q' to quit or any other key to continue:");
if (input != 'q')
{
runAgain = true;
}
所以去掉这个设置
runAgain = false;
来自 if 语句。
另一个问题是 scanf 的这个调用
scanf("%c", &input);
必须跟随问题
printf("Run program again? Type 'q' to quit or any other key to continue:");
而且格式字符串必须包含一个前导空白
scanf(" %c", &input);
^^^^^
否则将从输入 stream 中读取空白字符。那是你需要写的
printf("Run program again? Type 'q' to quit or any other key to continue:");
scanf(" %c", &input);
runAgain = input != 'q' && input != 'Q';
在要求用户再次运行之前,要确保runAgain
为false
,你会遇到很多麻烦。 这不是你想的那样:
if (solFound != true)
{
printf("No solution found\n\n");
runAgain = false;
}
一旦solFound
变为true
,它就会保持这种状态,如果程序循环时没有解决方案,您将无法打印“未找到解决方案”以及无法将runAgain
更改为 false。
如果runAgain
已经是true
,这会导致问题:
if (input != 'q')
{
runAgain = true;
}
这使您可以将false
(如果没有解决方案)改回true
(通过输入'q'
以外的内容)。 但是输入'q'
不能将true
变为false
!
只有当runAgain
假并且您输入'q'
时问题才会停止。
如果您只想根据q
的输入停止,您可以消除第一个块中solFound
和runAgain
之间的连接,并将第二个块替换为:
runAgain = (input != 'q');
这样runAgain
总是会改变以匹配用户的选择,永远不会单独使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.