【发布时间】:2022-01-16 17:50:51
【问题描述】:
如何编写一个程序来读取输入字符串并将该字符串转换为浮点数。
我对 double convert_to_double (char *) 的功能有点卡住了:
#include <stdlib.h>
#include <string.h>
double convert_to_double (char *);
int main(void)
{
char *s;
s = malloc(10 * sizeof(char));
printf("Enter text: ");
fgets(str, 10, stdin);
printf("The number is %lf", convert_to_double (str));
return 0;
}
double convert_to_double (char *str)
{
char *s;
double result;
result = strtod(str, &s);
if (s != NULL)
{
char *anotherEnd;
double anotherResult = strtod(s, &anotherEnd);
}
if (isalnum(s) == 0)
{
printf("Wrong digit entered..");
}
return result;
}
【问题讨论】:
-
你没有在函数的任何地方使用
str。你只是用两个未初始化的变量调用strtod(s, &ptr); -
我可以建议使用
scanf("%lf", &myDouble)之类的东西吗?检查返回值? -
@phuclv 我改了,你是这个意思吗?
-
什么是带有符号和运算符的示例输入?您对此输入的期望输出是什么?