C++ 将X提高到N的幂次方。代码不适用于负指数
我正在编写一个代码,它必须计算一个指数幂的基数。如果我输入任意基和非负指数,代码似乎是正确的 代码如下:C++ 将X提高到N的幂次方。代码不适用于负指数,c++,C++,我正在编写一个代码,它必须计算一个指数幂的基数。如果我输入任意基和非负指数,代码似乎是正确的 代码如下: #include <iostream> using namespace std; int n; //The Exponent int x; //The Base double result; int main(){ pleaseInput: cout << "Enter Base: "; cin >> x; cout
#include <iostream>
using namespace std;
int n; //The Exponent
int x; //The Base
double result;
int main(){
pleaseInput:
cout << "Enter Base: ";
cin >> x;
cout << "Now enter Exponent: ";
cin >> n;
//If the base is 0 could be tricky...
if(x==0){
if(n==0){
//0 ^ 0 = 1
result = 1;
}else if(n>0){
//0 ^ 3 = 0
result = 0;
}else if(n<0){
//0 ^ -2 is undefined.
cout << "0 to the power of a negative exponent is an undefined math operation. Please enter valid data. " << endl;
goto pleaseInput;
}
//If the base is other than 0...
}else{
//If the exponent is not 0...
if(n!=0){
//Make the exponent unsigned to know the amoun of iterations regardless its sign.
unsigned int exp = (unsigned int)n;
result = 1;
for(int i=0;i<exp;i++){
result *= x;
}
//If the exponent was negative...
if(n<0){
result = 1/result;
}
//If X^0....
}else{
result = 1;
}
cout << x <<" to the power of "<< n <<" equals "<< result << endl;
}
}
#包括
使用名称空间std;
int n//指数
int x//基地
双重结果;
int main(){
请输入:
cout>x;
cout>n;
//如果基数为0,可能会很棘手。。。
如果(x==0){
如果(n==0){
//0 ^ 0 = 1
结果=1;
}否则,如果(n>0){
//0 ^ 3 = 0
结果=0;
}否则如果(n首先,如果我做得不好,请原谅,但这是我第一次
在OP上的代码中,有一句话:
unsigned int exp = (unsigned int)n;
我使用它是为了从指数中删除可能的“-”符号,以便根据需要多次迭代循环
@RichardCriten告诉我这句话没有达到我的预期,我最终意识到实现这一点的方法是:
unsigned int exp = abs(n);
谢谢大家的帮助!此行unsigned int exp=(unsigned int)n、
不做你想做的事。当n
为负数时,使用调试器并在赋值后检查exp
。仅供参考,有一个标准函数std::pow可以做这件事,假设这不是家庭作业问题。仅供参考2.0:=如你所愿thinking@Richard克里顿:信不信由你,我从来没有使用过调试器,所以我是ac谢谢!这很好,如果你想成为一名优秀的程序员,它是第二个最重要的工具(第一个是你的大脑)