c - 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());
}
解决方案
两个问题:
该声明
while (do_again == 'Y');
相当于
while (do_again == 'Y') { // Empty body }
循环体是行尾的单个分号
当您使用该变量
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
调用以某种方式失败,会发生什么?
推荐阅读
- python - 将上下文管理器与 psycopg2 一起使用
- spring - Spring批量动态IN查询
- graphql - 如何格式化来自 java/groovy 客户端的 NewRelic NerdGraph API 调用?
- json - 为什么当代码实际工作时 Vue 会抱怨
- flutter - Flutter中的AlignmentDirectional和AlignmentGeometry是什么
- python - conjur python api thorwing ModuleNotFoundError: No module named 'config'
- python - 递归地按 n 缩放(单个)链表
- c# - C# 如何将 json 项目数组添加到 ExpandoObject?
- javascript - HTML中的Javascript,努力使for循环为按钮工作
- ruby-on-rails - 时间前用文字 i18n