gpt4 book ai didi

c - 我如何知道 scanf 输入的是字符还是 float ?

转载 作者:行者123 更新时间:2023-11-30 14:33:02 25 4
gpt4 key购买 nike

我正在尝试制作一个没有任何错误的简单计算器,但此外,例如,如果我输入“a”,程序会有意外的输出。基本上我的问题是我该怎么做才能让程序在我输入字符时显示警告。也许 scanf 返回任何有用的值?

最佳答案

您可以简单地使用 scanf 提供的标志来扫描整数。

int main()
{
float nb;

if (scanf("%f", &v) == 1) {
printf("Is float !\n");
} else {
printf("Not a float !\n");
}
return 0;
}

scanf 返回成功读取的标志数,因此如果该数字不同于 1(在本例中),则意味着 scanf 无法将您的输入转换为浮点型。

添加的情况下:

int main()
{
float a;
float b;

if (scanf("%f +%f", &a, &b) == 2) {
printf("Result is %f\n", a + b);
} else {
printf("Error !\n");
return 1;
}
return 0;
}

This works but you have to write the exact scanf string. I suggest you to read the input line as a string instead, and then parse it using strtol or other functions.

关于c - 我如何知道 scanf 输入的是字符还是 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513637/

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