+ 1
Didn’t get why is it 34 in output, when I write X =3, n = 1...it has to be X...what am I doing with my life...
#include <iostream> //у = х^(1^2)+ х^(2^2)+...+_• using namespace std; int main() { int n,p; int x; int result = 0; cin>>x; cin>>n; x = p; if(n!=1){ for(int i = 2; i<=n;i++){ for(int k =1; k <=i*i; k++){ x=x*x; } result = result +x; } //x - its x^1 cout<<result+x; }else cout<<x; }
4 odpowiedzi
+ 1
Ah, alright. Well, the problem is that you modify x directly in your loop, so it increases and increases while it should remain its initial value. You need to use some temporary variables here. Here is a solution without <cmath>:
https://code.sololearn.com/c1hZOE28Gyrc/?ref=app
+ 2
wow.... thanks!!!
+ 1
You could ease your life quite a bit if you used existing libraries. <cmath> provides a lot of maths functionality you can use instead of writing all those loops by yourself. This is how a simplified version could look:
https://code.sololearn.com/cR8lCASrduyl/?ref=app
Here you can find an overview of its entire functionality:
http://www.cplusplus.com/reference/cmath/
On a sidenote, the problem is most likely related to the statement
x = p;
Here, p is still not initialized, since you never provided a value for it, so it has some garbage value which was stored in that particular memory cell before, and you set x to that garbage value too, resulting in x nlt being the number the user entered before. Maybe you meant to write
p = x;
instead, so that p equals the value of x?
+ 1
i woud like to use math.h, but my task is to write code without it