首页 > 解决方案 > C 编程 - 关于 while 循环再次提示用户问题

问题描述

在这个例子中,我试图编写一个程序,让用户解决二次方程。最后,如果他们按 y/Y,他们可以重新启动程序。如果他们按 n/N,程序将退出,如果他们按任何其他,程序应再次提示他们输入 ay/Y/N/n。

不幸的是,我最终似乎无法正确运行此逻辑。任何想法为什么?谢谢

#include <ctype.h> //in order to use toupper
#include <stdio.h> // * Solution of a*x*x + b*x + c = 0 *
#include <math.h>

int main(void)
{
double a, b, c, root1, root2;
char do_again;
while (do_again == 'Y');
printf("Input the coefficient a => ");
scanf("%lf", &a);
printf("Input the coefficient b => ");
scanf("%lf", &b);
printf("Input the coefficient c => ");
scanf("%lf", &c);
if (a == 0)
{
printf("You have entered a = 0.\n");
printf("Only one root: %8.3f", -c/b);
}
else 
{
    root1 = (- b + sqrt(b*b-4*a*c))/(2*a);
    root2 = (- b - sqrt(b*b-4*a*c))/(2*a);
    printf("The first root is %8.3f\n", root1);
    printf("The second root is %8.3f\n", root2);
}
printf("Solve again (y/n)? ");
fflush(stdin);
do_again = toupper(getchar());
if (do_again !='Y' && do_again !='N' )  
    printf("Please try again");
    do_again = toupper(getchar());
}

标签: cwhile-loop

解决方案


两个问题:

  1. 该声明

    while (do_again == 'Y');
    

    相当于

    while (do_again == 'Y')
    {
        // Empty body
    }
    

    循环体是行尾的单个分号

  2. 当您使用该变量do_again时,它是未初始化的。它的价值将是不确定的。您需要在使用它们之前初始化所有变量。

这两个问题一起意味着您要么有一个无限循环(如果do_again恰好等于'Y'),要么根本没有循环。


您的代码中还有其他问题,例如

if (do_again !='Y' && do_again !='N' )  
    printf("Please try again");
    do_again = toupper(getchar());

这相当于

if (do_again !='Y' && do_again !='N' )  
    printf("Please try again");
do_again = toupper(getchar());

也就是说,只有printf调用在内部if,分配总是无条件地执行。

您还缺乏错误检查。例如,如果其中一个scanf调用以某种方式失败,会发生什么?


推荐阅读