我已經看過扔在Converting Double to String in C++和 Convert double to string C++? 的建議,但我被要求創建一個函數的非OOP採取了一倍,並返回一個std :: string的只用數學。我已經能夠做到這一點在過去與int int:雙字符串C++使用數學
std::string toString(int value) {
string result = "";
bool negative = false;
if (value < 0) {
negative = true;
value *= (-1);
}
do {
string tmpstr = "0";
tmpstr[0] += value%10;
result = tmpstr + result;
value /= 10;
} while (value != 0);
if (negative) {
result = "-" + result;
}
return result;
}
但問題是,它使用檢查大於零繼續前進。我一直在想這樣
if (value < 0){
value *= 10;
}
我的事情,這應該在10%纔去,但我不知道。每次我嘗試我得到一個整數,而不是小數。
例如我給它125.5(251/2的結果),它輸出1255.雖然在某些情況下我只得到125.任何幫助都會很好。
更新:選擇的解決方案
std::string toString(float value){
bool negative = false;
if (value < 0) {
negative = true;
value *= (-1);
}
int v1 = value; // get the whole part
value -= v1; // get the decimal/fractional part
//convert and keep the whole number part
std::string str1 = toString(v1);
std::string result = "";
do {
value *= 10;
int tmpint = value;
value -= tmpint;
string tmpstr = "0";
tmpstr[0] += tmpint % 10;
result = tmpstr + result;
value /= 10;
} while (value != 0);
result = str1 + "." + result;
if (negative) {
result = "-" + result;
}
return result;
}
['std :: to_string' from](http://en.cppreference.com/w/cpp/string/basic_string/to_string)。 –
Xeo
2012-02-14 06:25:23
@Xeo我被要求使用數學算法而不是方法調用 – gardian06 2012-02-14 06:26:22