gpt4 book ai didi

c++ - 将科学计数法转换为十进制

转载 作者:行者123 更新时间:2023-11-30 03:04:42 29 4
gpt4 key购买 nike

我正尝试在 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;
}

我试过到处搜索如何转换它,我读到我可以在流上使用 << fixed << 或 .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

编辑:拼写错误

最佳答案

变量 powanswer 是一个 float ,但您想将它打印为一个整数

怎么样:

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

稍后也使用 powanswer_int

关于c++ - 将科学计数法转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445258/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com