0

Hello, i need to make program which can do squaring, so x^n. I can do it with pow(x,n):

#include <iostream>
#include <cmath>
using namespace std;
int main()  
{
double x, c;
int n; 
cout << "Alap = "; cin >> x;
cout << "Kitevo = "; cin >> n;
if (n < 0)
{
   cerr << "Csak termeszetes szam lehet a kitevo!" << endl;
   return -1;
}
c = pow(x,n);
cout << "Hatvanyertek = " << c;
return 0; 
}

But i need to do it without pow(,) and only with #include <iostream>. So i need to do x*x*...*x with n times... I think i need to use a while loop but i have no idea how. Can anybody help me? (sorry for bad English)

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Escom
0

what you need to use is a for(), since it is better because you can instruct the cycle to do the procedure as many times as you want. Like this:

double x,multiplication=1; //create a second variable so you won't lose your x value
for (int i=0;i<n;i++){
   multiplication=multiplication*x; //multiply your x value to your stored multiplication in the variable you created
}

or if you were using a while(), you could do it this way:

double x,multiplication=1,i=0; //i is your centinel to stop the cycle
while (i<n){
   multiplication=multiplication*x;
   i++;
}

Edited by pyTony: fixed formating

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.