腾讯2014春季笔试题:double数的解析

来源:互联网 发布:mac如何打出罗马数字 编辑:程序博客网 时间:2024/04/19 22:08

根据下面对double数的定义,编写一个函数去parse一个字符串至double



double数指数部分(即e/E后面的数字),若没有应该为false,但是照这图画的意思,e/E后面若不跟数字也可以。下面的程序则处理为false

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <assert.h>   
  3.   
  4. #define bool int  
  5. #define false 0  
  6. #define true 1  
  7.   
  8. bool isNum(const char ch)  
  9. {  
  10.     if ((ch<='9')&&(ch>='0'))  
  11.         return true;  
  12.     else  
  13.         return false;  
  14. }  
  15.   
  16. bool ParseNumber(const char *s, double *d)  
  17. {  
  18.     int i = 0;  
  19.     int a = 0, b = 0;   
  20.     double c = 0.0, f = 10.0; // -a.cE(e)(+/-)b  
  21.     int flag1 = 1, flag2 = 1; // 1表示正,-1表示负  
  22.     if (s[i] == '-') {  
  23.         flag1 = -1;  
  24.         i++;  
  25.     }  
  26.     if (s[i] == 0) {  
  27.         i++;  
  28.     }  
  29.     else if ((s[i]<='9') && (s[i]>='1')) {  
  30.         a += s[i] - '0';  
  31.         while (isNum(s[++i])) {  
  32.             a = a*10 + s[i] - '0';  
  33.         }  
  34.     }  
  35.     if (s[i] == '.') {  
  36.         while (isNum(s[++i])) {  
  37.             c += (s[i]-'0')/f;  
  38.             f *= 10.0;  
  39.         }  
  40.     }  
  41.     if ((s[i] == 'e') || (s[i] == 'E')) {  
  42.         i++;  
  43.         if (s[i] == '+') {  
  44.             i++;  
  45.         }  
  46.         else if (s[i] == '-') {  
  47.             flag2 = -1;  
  48.             i++;  
  49.         }  
  50.         if (!isNum(s[i])) //e(E)后面没有数字则错误  
  51.             return false;  
  52.         while (isNum(s[i])) {  
  53.             b = b*10 + s[i] - '0';   
  54.             i++;  
  55.         }  
  56.     }  
  57.     if (s[i] == '\0') {  
  58.         c += a;  
  59.         if (flag1 == -1)  
  60.             c = -c;  
  61.         if (flag2 == -1) {  
  62.             while (b--)  
  63.                 c /= 10.0;  
  64.         }  
  65.         else {  
  66.             while (b--)  
  67.                 c *= 10.0;  
  68.         }  
  69.         *d = c;  
  70.         return true;  
  71.     }  
  72.     else  
  73.         return false;      
  74. }  
  75.   
  76. int main(void)  
  77. {  
  78.     double d;  
  79.     assert(ParseNumber("10.25e+12", &d));  
  80.     assert(d == 10.25e+12);  
  81.     assert(!ParseNumber("101.01e-", &d));  
  82.     return 0;  

0 0