Reputation: 189
I'm trying to do the challenge on http://www.cstutoringcenter.com/problems/problems.php?id=2 and I'm having problems converting scientific notation to decimal notation, which I need to add the exponent together:
Here is my code so far:
#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;
}
I've tried searching everywhere on how to convert it, and I read I can use << fixed << on the stream, or .setf(ios::fixed) but neither seems to be working for me and I'm not sure what I'm doing wrong.
As marked in the code, here is the current output:
2^20 = 1.04858e+06 => 1+.+0+4+8+5+8+e+++0+6 => 32
What I want and expect to see is:
2^20 = 1048576 => 1+0+4+8+5+7+6 => 31
Edit: Spelling mistake
Upvotes: 1
Views: 3218
Reputation: 409136
The variable powanswer
is a float
, but you want to print it as an integer
?
How about something like:
int powanswer_int = (int) powanswer;
cout << FIRST << "^" << SECOND << " = " << powanswer_int << " => ";
And use the powanswer_int
later as well.
Upvotes: 3