简体   繁体   English

C 编程 - 关于 while 循环再次提示用户问题

[英]C Programming - Regarding while loops to prompt user question again

In this example, I am trying to code a program which let users solve qudratic equations.在这个例子中,我试图编写一个程序,让用户解决二次方程。 At the end, should if they press y/Y, they can restart the program.最后,如果他们按 y/Y,他们可以重新启动程序。 If they pressed n/N, the program will exit and if they press any other, the program should prompt them again for either ay/Y/N/n.如果他们按下 n/N,程序将退出,如果他们按下任何其他键,程序应再次提示他们输入 ay/Y/N/n。

Unfortunately, I can't seem to run this logic at the end properly.不幸的是,我似乎无法在最后正确运行此逻辑。 Any ideas why?任何想法为什么? Thanks谢谢

#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());
}

Two problems:两个问题:

  1. The statement该声明

    while (do_again == 'Y');

    is equivalent to相当于

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

    The loop body is the single semicolon at the end of the line循环体是行尾的单个分号

  2. When you use the variable do_again it's uninitialized .当您使用变量do_again它是uninitialized It's value will be indeterminate .它的价值将是不确定的 You need to initialize all variables before you use them.您需要在使用它们之前初始化所有变量。

These two problems together means that either you have an infinite loop (if do_again just happens to be equal to 'Y' ), or no loop at all.这两个问题一起意味着要么有一个无限循环(如果do_again恰好等于'Y' ),要么根本没有循环。


There's also other problems in your code, for example例如,您的代码中还有其他问题

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

which is equivalent to这相当于

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

That is, only the printf call is inside the if , the assignment is always and unconditionally performed.也就是说,只有printf调用在if ,赋值总是无条件地执行。

You also lack error checking.你也缺乏错误检查。 What happens if, for example, one of the scanf calls fails one way or another?例如,如果一个scanf调用以某种方式失败,会发生什么情况?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM