很多人都写过这个标题的文章,但本文要解决的是确保负数的string和double也可以进行转换。
代码如下:
string转double
1 double stringToDouble(string num) 2 { 3 bool minus = false; //标记是否是负数 4 string real = num; //real表示num的绝对值 5 if (num.at(0) == ‘-‘) 6 { 7 minus = true; 8 real = num.substr(1, num.size()-1); 9 } 10 11 char c; 12 int i = 0; 13 double result = 0.0 , dec = 10.0; 14 bool isDec = false; //标记是否有小数 15 unsigned long size = real.size(); 16 while(i < size) 17 { 18 c = real.at(i); 19 if (c == ‘.‘) 20 {//包含小数 21 isDec = true; 22 i++; 23 continue; 24 } 25 if (!isDec) 26 { 27 result = result*10 + c - ‘0‘; 28 } 29 else 30 {//识别小数点之后都进入这个分支 31 result = result + (c - ‘0‘)/dec; 32 dec *= 10; 33 } 34 i++; 35 } 36 37 if (minus == true) { 38 result = -result; 39 } 40 41 return result; 42 }
double转string
string Chars::doubleToString(double num) { char str[256]; sprintf(str, "%lf", num); string result = str; return result; }
by 一棵球
时间: 2024-12-18 19:04:33