while循环不会执行
while loop will not execute
我需要一个 while 循环来只接受正数。我写了一个 while 循环,但它不会执行,我不确定哪里出了问题。我的代码在 for while 循环中运行良好,但是当我输入负数和 运行 代码时,它会打印出输入,然后重新提示用户。我只是想让它重新提示,而不是打印输入。
如果有人能提供帮助,谢谢。
这将打印输入,然后重新提示用户
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
do
{
change = get_float("Change: ");
printf("%f\n", change);
}
while (change < 1);
}
这根本不会执行
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
while (change < 1)
{
change = get_float("Change: ");
printf("%f\n", change);
}
}
在第一个中,停止在循环内执行 printf
。
在第二个中,您在将值存储到其中之前测试 change
的值,这是未定义的行为。
试试下面的方法。查看评论解释
使用 do..while 循环
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
do
{
change = get_float("Change: ");
}
while (change < 1);
printf("%f\n", change);
}
使用 while 循环
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
change = get_float("Change: "); //Capture value for first time
while (change < 1) //Check if input value is negative
{
change = get_float("Change: "); //If negative ask for input again
}
printf("%f\n", change); // If value is positive, while loop passed over and value printed
}
我需要一个 while 循环来只接受正数。我写了一个 while 循环,但它不会执行,我不确定哪里出了问题。我的代码在 for while 循环中运行良好,但是当我输入负数和 运行 代码时,它会打印出输入,然后重新提示用户。我只是想让它重新提示,而不是打印输入。
如果有人能提供帮助,谢谢。
这将打印输入,然后重新提示用户
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
do
{
change = get_float("Change: ");
printf("%f\n", change);
}
while (change < 1);
}
这根本不会执行
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
while (change < 1)
{
change = get_float("Change: ");
printf("%f\n", change);
}
}
在第一个中,停止在循环内执行 printf
。
在第二个中,您在将值存储到其中之前测试 change
的值,这是未定义的行为。
试试下面的方法。查看评论解释
使用 do..while 循环
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
do
{
change = get_float("Change: ");
}
while (change < 1);
printf("%f\n", change);
}
使用 while 循环
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float change;
change = get_float("Change: "); //Capture value for first time
while (change < 1) //Check if input value is negative
{
change = get_float("Change: "); //If negative ask for input again
}
printf("%f\n", change); // If value is positive, while loop passed over and value printed
}