我正在尝试开放课件 CS106b 作业 1。我遇到了问题 4,它需要使用递归将整数写入字符串转换器。我们不允许使用任何执行整数转换的库函数。
问题是,在每个“递归级别”之后,代码都不会跟踪前一个字符串,因此我无法附加和构建字符串。
#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;
}
我的调试输出显示它只返回最后一位数字:
谁能建议如何成功附加到字符串ConvertedToString
以便我返回整个转换后的整数?