gpt4 book ai didi

c - 使用 "for"循环创建检查输入值的循环是否正确?

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:17 25 4
gpt4 key购买 nike

我需要编写一个程序来请求两个 float 并打印出他们的差异除以他们的产品,并让程序循环通过对输入值,直到用户输入非数字输入。我需要使用 scanf 来获取输入。

因此,据我所知,scanf 会为 true/false 返回值 0 或 1,因此我虽然对其进行了测试以完成问题的最后一部分,但我正在尝试弄清楚如何确保循环返回要求输入。

我的代码是:

int main()    
{
double num1, num2, different, product, answer;

printf("please enter 2 floatig point numbers:\n");
printf("number one is?\n");
while (scanf("%lf", &num1) ==1)
{
printf("number two is?\n");
while (scanf("%lf", &num2) ==1)
{
if (num1 > num2)
{
different = num1 - num2;
}

if (num2 > num1)
{
different = num2 - num1;
}

if (num1 == num2)
{
different = 0;
}

product = num1*num2;
answer = different/product;
printf("%lf", answer);
}
printf("you're out!");
}
printf("you're out!");
}

示例输入:

first num 4.5
second num 3.5

输出:

please enter 2 floatig point numbers:
number one is?
4.5
number two is?
3.5
0.063492

我得到了正确答案并且程序继续运行,但我正在寻找返回输入请求的解决方案。

最佳答案

您应该首先注意,无论是什么让您的 scanf 第一次失败,都可能会导致它第二次失败。所以像这样的循环:

while (scanf("%lf", &a) != 1);

可能变成无限循环

此外,当同时读取两个或多个值时,很难跟踪读取的内容和未读取的内容。因此,我建议以如下形式逐一阅读这些值:

void clear_line()
{
char c;
while (scanf("%c", &c) == 1)
if (c == '\n')
return;
}

double read_value(const char *message)
{
double d;

while (1)
{
printf("%s", message);
if (scanf("%lf", &d) == 1)
return d;
if (feof(stdin))
{
printf("Unexpected end of file\n");
return 0;
}
printf("Invalid input\n");
clear_line();
}
}

...
num1 = read_value("Enter first number: ");
num2 = read_value("Enter second number: ");
if (feof(stdin))
/* handle error */

这基本上是尝试读取值,直到用户生成正确的值。如果输入不正确,一行输入将被消耗并丢弃,因此用户输入的任何剩余内容都不会影响下一个 scanf 并产生错误链。

关于c - 使用 "for"循环创建检查输入值的循环是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14501566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com