将科学记数法转换为十进制

时间:2011-12-09 12:07:08

标签: c++

我试图在http://www.cstutoringcenter.com/problems/problems.php?id=2上进行挑战,并且我在将科学记数法转换为十进制记法时遇到问题,我需要将指数加在一起:

到目前为止,这是我的代码:

#define FIRST 2
#define SECOND 20

#include <iostream>
#include <cmath>
#include <sstream>
#include <iomanip>

using namespace std;

int main()
{
    // Give variables initial setting
    int total = 0;
    float powanswer = 0;

    // Get rid of scientific notation for large numbers
    stringstream ss;
    ss.setf(ios::fixed);
    ss << pow(FIRST,SECOND);
    ss >> powanswer;


    // Output
    // Expected: 2^20 = 1048576 => 1+0+4+8+5+7+6 => 31
    // Outcome: 2^20 = 1.04858e+06  => 1+.+0+4+8+5+8+e+++0+6 => 32
    cout << FIRST << "^" << SECOND << " = " << powanswer << "  => ";


    // Convert power int to string
    string ResultText = "";
    stringstream convert;
    convert << powanswer;
    ResultText = convert.str();

    // Loop over total
    for (int x=0; x<ResultText.size(); x++)
    {

        // Convert character to integer
        int ResultNum = 0;
        stringstream convert;
        convert << ResultText[x];
        convert >> ResultNum;
        total+=ResultNum;

        // Output
        cout << ResultText[x];
        ResultText.size()-1 == x ? cout << " => " : cout << "+";

    }
    cout << total << endl;
    return 0;
}

我已尝试在各地搜索如何转换它,我读过我可以使用&lt;&lt;固定&lt;&lt;在流上,或.setf(ios :: fixed),但似乎都不适合我,我不确定我做错了什么。

如代码中标记的,这是当前输出:

2^20 = 1.04858e+06  => 1+.+0+4+8+5+8+e+++0+6 => 32

我想要和希望看到的是:

2^20 = 1048576 => 1+0+4+8+5+7+6 => 31

编辑:拼写错误

1 个答案:

答案 0 :(得分:3)

变量powanswerfloat,但您想将其打印为integer

如下:

int powanswer_int = (int) powanswer;
cout << FIRST << "^" << SECOND << " = " << powanswer_int << "  => ";

稍后也使用powanswer_int