i want to write a code that calculate
1^1+2^2+3^3....10^10
but it gives a weird answer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespace std;
int main()
{
int sum=0;
for(int n=1;n<=10;n++) //which 'n' is the base
{
for(int p=1;p<=10;p++) //which 'p' is the power
{
sum=sum+(int) pow((float)n,p);
}
}
cout<<sum<<endl;
system("pause");
return 0;
}
LOL it's a good to make it i^i i wasn't focus thx alot
but i'm using Vc++ 2010 express and i need to write power in this way
sum=sum+(int) pow((double)n,p);
but it gives me the result with -
(i have stopped C++ for a year and i make this simple codes just to remember i think i need to review it again )
thx alot
and could u tell me which compilers r able to compile C++11
Oh that's due to overflow errors. int or long isn't guaranteed to be enough because you're dealing 10,000,000,000-something.
Here's working code for me.
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <cmath>
int main()
{
longlong sum = 0LL;
for (int i = 1; i <= 10; i++)
{
sum = sum + std::pow(i, i);
}
std::cout << sum << std::endl;
return 0;
}
It gives same result as wolfram alpha.
____________________________
c++11 stuff:
I was able to compile this fine without C++11, but your compiler should have a flag
-std=c++11
You should be having C++11, there's really no reason not to in 2014, but it isn't the source of your problem anyway.
Edit: Oh I didn't see you're saying you're using VS2010, I'm not sure about the compiler used in that IDE. See if my code compiles correctly. If VS2010 hasn't been updated since 2010, then it's going to be outdated. Why not VS2013?