【问题标题】:C Programming - Regarding while loops to prompt user question againC 编程 - 关于 while 循环再次提示用户问题
【发布时间】:2020-03-28 22:11:13
【问题描述】:

在这个例子中,我试图编写一个程序,让用户解决二次方程。最后,如果他们按 y/Y,他们可以重新启动程序。如果他们按 n/N,程序将退出,如果他们按任何其他,程序应该再次提示他们输入 y/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());
}

【问题讨论】:

  • 请正确缩进你的代码!那是不可读的。

标签: c while-loop


【解决方案1】:

两个问题:

  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 调用之一以某种方式失败,会发生什么情况?

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多