gpt4 book ai didi

c - 如何限制用户在C中输入一位小数点的 float

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

在C语言中将用户的输入限制为一位小数的程序。

例如:

输入等级:5//可接受
输入等级:8.5//可接受
输入成绩:6.467//不接受,重新输入成绩

#include <stdio.h>
#include <math.h>

main()
{
double grade[8];
int i;

for (i = 0; i < 8; i++) {
printf("Insert grade: ");
scanf("%f", &grade[i]);
}
}

最佳答案

您必须将数据作为字符串输入,然后检查它是否只有一位小数。

无法输入浮点值然后检查小数位;因为浮点值在内部存储为二进制位置,并且在大多数情况下保持输入值的近似值。

输入代码可能如下所示:

char temp[20];
if ( 1 != scanf("%19s", temp) )
return EXIT_FAILURE;

// code to check for decimal place goes here - I'm purposefully not
// showing it as this looks like homework!

// once we have checked that the input is correct, then convert to double
grade[i] = strtod(temp, NULL);

关于c - 如何限制用户在C中输入一位小数点的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494336/

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