C++:用两种不同的循环语句实现x的n次方求解
发布网友
发布时间:2022-05-29 17:37
我来回答
共3个回答
热心网友
时间:2023-10-29 11:32
一个用for循环,一个用while循环
运行过,一切正常~
#include <iostream>
using namespace std;
void __for(int x, int n)
{
double result = 1.0;
for(int i = 0; i < n; i++)
result *= x;
cout << x << "的" << n << "次方是:" << result << endl;
}
void __while(int x, int n)
{
double result = 1.0;
int j = 0;
while(n != 0)
{
result *= x;
n--;
j++;
}
cout << x << "的" << j << "次方是:" << result << endl;
}
void main()
{
int x;
int n;
cout << "输入x、n:";
cin >> x >> n;
__for(x, n);
__while(x, n);
}
热心网友
时间:2023-10-29 11:32
#include<stdio.h>
main()
{int x,n;
imt i=0;
int result;
scanf("%d %d",x,n);
while(i<n)
{result*=x;
i++;
}
printf("%d",result);
}
#include<stdio.h>
main()
{int x,n;
imt i=0;
int result;
scanf("%d %d",x,n);
for(i=0;i<n;i++)
{result*=x;
}
printf("%d",result);
}
热心网友
时间:2023-10-29 11:33
#include <iostream>
using namespace std;
double doit( int iX, int iY )
{
if( iY == 0 )
{
return 1;
}
double dResult = iX;
const int iYM = iY>0?iY:-iY;
for( int i=1; i<iYM; ++i )
{
dResult *= iX;
}
if( iY>0 )
{
return dResult;
}
else
{
return 1.0/dResult;
}
}
void main()
{
cout<< doit( 10, 3 ) << endl;
cout<< doit( 2, -1 ) << endl;
}