我试图打开课件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;
}
我调试输出显示,它只返回最后一个数字:
任何人都可以建议如何成功地追加到字符串ConvertedToString
让我回到了整个转换的整数?
虽然你的问题已经得到解答,但我有一个改进建议。松散使用浮点(双精度型)。这是不需要的,可能会导致舍入问题,效率较低,特别是在没有浮点单元的平台上。它也看起来像我的功能不会为值<= 0工作。 – Eelke 2012-08-12 04:49:31