[英]String converts to an integer instead of double
I want my function to convert a string to a double but if I type for example '22.4' it will output '22'. 我希望我的函数将字符串转换为双精度型,但是如果输入例如“ 22.4”,它将输出“ 22”。 How do I get it to output a double?(USING fgets) I've read other questions that had answers saying use sscanf but is there a way for using fgets? 如何获取输出的double?(使用fgets)我读过其他有答案的问题,说使用sscanf,但是有使用fgets的方法吗?
double getDouble(char message[]){
double val;
double var = 0.0;
char input[80];
do{
printf("%s\n", message);
fgets(input, 80, stdin);
if (input[strlen(input)-1] == '\n'){
input[strlen(input)-1] = '\0';
}
val = atof(input);
if (val != 0.0){
var = 1.0;
}
else{
printf("Error. Please try again.(Only entering numbers is valid)\n");
}
}while(var == 0.0);
printf("The result is: %f\n", val);
return val;
}
Here is a working example. 这是一个工作示例。
Some modifications: 一些修改:
near_equal()
function, as testing equality of doubles is dangerous. 使用near_equal()
函数很危险,因为测试双精度是否相等。 var = 0.0
, why not just use an int
? 为何不使用int
而不是使用诸如var = 0.0
的双标记? Checking the return value of fgets
is always a good idea. 检查fgets
的返回值始终是一个好主意。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define BUFFSIZE 80 #define EPSILON 1e-8 double getDouble(char message[]); int double_equal(double a, double b); int main(void) { double num; num = getDouble("Enter a real number: "); printf("The result is: %.1f\\n", num); printf("The number you entered was %g\\n", num); return 0; } double getDouble(char message[]) { double val; char input[BUFFSIZE]; int found = 0; do { printf("%s\\n", message); if (fgets(input, BUFFSIZE, stdin) != NULL) { if (input[strlen(input)-1] == '\\n'){ input[strlen(input)-1] = '\\0'; } val = atof(input); if (!double_equal(val, 0.0)) { found = 1; } else { printf("Error. Please try again.(Only entering numbers is valid)\\n"); } } } while (found == 0); return val; } int double_equal(double a, double b) { return fabs(ab) < EPSILON; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.