如何写一个数字字符串转换为数值的函数呀??
比如str="12.23243"转换后为floati=12.23243;C语言和C++都行呀...
比如str="12.23243"转换后为float i =12.23243;
C语言和C++都行呀 展开
C语言和C++都行呀 展开
1个回答
展开全部
#include <ctype.h>
/* atof: convert string s to double */
double atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
From 'The C Programing Language'
#include <stdio.h>
/* atof: convert string s to double */
double Atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; s[i] == ' '; i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; s[i] >= '0' && s[i] <= '9'; i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; s[i] >= '0' && s[i] <= '9'; i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
int main()
{
char str[100];
printf("输入一个字符串\n");
scanf("%s",str);
printf("转换后为 %lf\n",Atof(str));
return 0;
}
/* atof: convert string s to double */
double atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
From 'The C Programing Language'
#include <stdio.h>
/* atof: convert string s to double */
double Atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; s[i] == ' '; i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; s[i] >= '0' && s[i] <= '9'; i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; s[i] >= '0' && s[i] <= '9'; i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
int main()
{
char str[100];
printf("输入一个字符串\n");
scanf("%s",str);
printf("转换后为 %lf\n",Atof(str));
return 0;
}
参考资料: http://topic.csdn.net/t/20030707/12/1998900.html
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询