2012-08-12 65 views
1

我试图打开课件CS106b分配1.我被陷在问题4这就需要使用递归的写入字符串转换为整数。我们不允许使用任何执行整数转换的库函数。C++和递归:函数整数到

的问题是,每一个“递归级别”后的代码不保留以前的字符串的轨道,因此我不能追加和构建到字符串。

#include <iostream> 
#include <string> 
#include "console.h" 
#include "simpio.h" 
using namespace std; 

/* Function prototypes */ 

string intToString(int n); 
int stringToInt(string str); 

/* Main program */ 

int main() { 
    // [TODO: fill in the code] 
    int n = getInteger("Enter number for conversion to String: "); 
    cout<< "Converted to String: "<<intToString(n); 
    return 0; 
} 

//Functions 

string intToString(int n){ 
    double toBeDecomposed = n; 
    string convertedToString; 
    char ch; 
    string tempString; 

    if((double)(toBeDecomposed/10) >= 0.1){ 

     int lastDigit = (int)toBeDecomposed%10; 

     toBeDecomposed = (int)(toBeDecomposed/10); 

     intToString(toBeDecomposed); 

     if (lastDigit == 0) { 
      ch = '0'; 
     } 
     else if (lastDigit == 1) { 
      ch = '1'; 
     } 
     else if (lastDigit == 2) { 
      ch = '2'; 
     } 
     else if (lastDigit == 3) { 
      ch = '3'; 
     } 
     else if (lastDigit == 4) { 
      ch = '4'; 
     } 
     else if (lastDigit == 5) { 
      ch = '5'; 
     } 
     else if (lastDigit == 6) { 
      ch = '6'; 
     } 
     else if (lastDigit == 7) { 
      ch = '7'; 
     } 
     else if (lastDigit == 8) { 
      ch = '8'; 
     } 
     else if (lastDigit == 9) { 
      ch = '9'; 
     } 

     tempString = string() + ch; 

     convertedToString = convertedToString.append(tempString); 

     cout<<convertedToString<<endl; 

    } 
    cout<<"Returning: "<<convertedToString<<endl; 

    return convertedToString; 
} 

int stringToInt(string str){ 
    return 0; 
} 

我调试输出显示,它只返回最后一个数字:

enter image description here

任何人都可以建议如何成功地追加到字符串ConvertedToString让我回到了整个转换的整数?

+1

虽然你的问题已经得到解答,但我有一个改进建议。松散使用浮点(双精度型)。这是不需要的,可能会导致舍入问题,效率较低,特别是在没有浮点单元的平台上。它也看起来像我的功能不会为值<= 0工作。 – Eelke 2012-08-12 04:49:31

回答

3

你没有做你的递归函数调用的结果什么。

提示是intToString返回 a string。当您致电intToString(toBeDecomposed);时,您会忽略该返回值。

捕获返回值,并用它做什么。

+0

doh!非常感谢它现在的工作!我所要做的就是添加任务:convertedToString = intToString(toBeDecomposed); – rrazd 2012-08-12 04:22:15

+0

一般来说,你会说我的代码编写得好,还是可以在某处改进?我试图提高我的代码质量,我不确定我的代码是否以“业余爱好者”的身份出现。 – rrazd 2012-08-12 04:24:30

+1

@rrazd:它至少可以改进一点,至少IMO。我首先将个人数字转换为类似'char digit = input%10 +'0';'而不是long'if'/'then' /'else'。 – 2012-08-12 04:26:44

1

您convertedToString变量是本地varible,所以每次intToString函数调用它创建新的,并在递归结束并返回它得到它包含了最后一个数字的最后convertedToString。

简单的解决方案是使其成为静态或全局。

+0

是的,也可以,谢谢! – rrazd 2012-08-12 04:26:40

+0

最受欢迎:--D – 2012-08-12 04:32:44