gpt4 book ai didi

c - 我如何检查用户的输入是否为 float ?

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

我想编写一个 if 语句,如果用户输入是 float ,则 X 发生,但我实际上不知道如何将其转换为代码。代码在下面,所以如果有人能帮助我,那就太好了。

// declare a variable
float i = 0;

// ask for an input
scanf( "%f", &i );

// if the input is a float
if() <--- DON'T KNOW WHAT TO PUT HERE
{
// print normally
printf();
}

// in all other cases
else
{
// print an error message
printf();
}

抱歉,如果这是一个非常简单的问题,但我是学习 C 的新手。

最佳答案

您检查 scanf 调用的返回值——它告诉您有多少转换成功:

if (scanf("%f", &i) == 1) {
// the input is a float
} else {
// all other cases -- print an error message
}

关于c - 我如何检查用户的输入是否为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361728/

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