0
trying to make a program that can calculate 2^n, 1<=n<=100,but I have some major issues in my code.The problem appears when n>=5
#include <iostream> using namespace std; int main() { int n,v[31]={2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},a=0; cin>>n; for(int i=1;i<n;i++) { for(int j=0;j<31;j++) { if(v[j]*2+a>9) { a=(v[j]*2+a)/10; v[j]=(v[j]*2+a)%10; } else { v[j]=(v[j]*2)+a; a=0; } } } for(int i=30;i>=0;i--)cout<<v[i]; return 0; }
5 odpowiedzi
+ 2
Why don't do something like this:
result = 2;
for (i=n;i<=0;i--){ result *=2 }
+ 1
I know where the mistake is.
In the first part of the if statement you are using the already modified a. Just replace it with this and everything should work fine.
...
if(v[j]*2+a>9){
v[j]=(v[j]*2+a);
a = v[j]/10;
v[j] = v[j]%10;
}
...
+ 1
No problem :)
0
because the size of the number is too big , 2^100 has 31 digits and the biggest data type I know, the unsigned long long has 19 digits (if I remember well)
0
worked like a charm, thank you Martin