C将char数组的部分转换为double [英] C convert section of char array to double
问题描述
我想将一个char数组的一个部分转换为double。例如我有:
I want to convert a section of a char array to a double. For example I have:
char in_string[] = "4014.84954";
说我要转换第一个 40
到值为 40.0
的double。我的代码到目前为止:
Say I want to convert the first 40
to a double with value 40.0
. My code so far:
#include <stdio.h>
#include <stdlib.h>
int main(int arg) {
char in_string[] = "4014.84954";
int i = 0;
for(i = 0; i <= sizeof(in_string); i++) {
printf("%c\n", in_string[i]);
printf("%f\n", atof(&in_string[i]));
}
}
在每个循环中 atof
它转换char数组从开始指针我一直供应到数组的结尾。输出为:
In each loop atof
it converts the char array from the starting pointer I supply all the way to the end of the array. The output is:
4
4014.849540
0
14.849540
1
14.849540
4
4.849540
.
0.849540
8
84954.000000 etc...
我只转换一个字符数组的一部分为双?这必须通过模块化,因为我真正的input_string是更复杂,但我会确保char是一个数字0-9。
How can I convert just a portion of a char array to a double? This must by modular because my real input_string is much more complicated, but I will ensure that the char is a number 0-9.
推荐答案
p>以下应该工作假设:
The following should work assuming:
我将确保char是一个数字0-9。
I will ensure that the char is a number 0-9.
double toDouble(const char* s, int start, int stop) {
unsigned long long int m = 1;
double ret = 0;
for (int i = stop; i >= start; i--) {
ret += (s[i] - '0') * m;
m *= 10;
}
return ret;
}
例如对于 23487
该函数将执行以下计算:
For example for the string 23487
the function will do this calculations:
ret = 0
ret += 7 * 1
ret += 8 * 10
ret += 4 * 100
ret += 3 * 1000
ret += 2 * 10000
ret = 23487
这篇关于C将char数组的部分转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!