我对其进行了重新排列,使其符合要求,但是在运行代码时,它返回“对'Power(int,int,int)的未定义引用”。我将其简化为一行,但是我不知道如何解决它。将其与我所做的类似示例进行比较似乎是有条理的。我相信问题在于它没有将“返回”传递回主体。
#include <iostream>
int Power( /* in */ int pow, /* in */ int x, /* out */ int &result); //prototype
using namespace std;
int main()
{
int pow;
int x;
int result;
cout << "Enter power: "; //prompt for integer in for power to be raised by
cin >> pow; //integer in
cout << "Enter value to be raised to power: "; //prompt for integer to be raised
cin >> x; //integer in
cout << Power(pow, x, result); /*function results output. returns input of Power function***
This line is the problem but why...
If I remove "(pow,x,result)" it will compile but it does not calculate properly.
If I take the while loop from the Power function by itself it calculates fine.
If I replace Power ((pow,x,result) with 'result' it makes a really big number...
*/
return 0; //return
}
int Power( /*in */ int pow, /*in */ int x, /*out */ int result); //Power function should calculate the result of raising 'x' to the 'pow' entered...
{
result = 1; //result is set at 1 by default
while (pow > 0) //while loop with pow set to greater than 0
{
result = result * x; //calculation for raising x by pow
pow--;
}
return result; //returning while loop results to function
}
答案 0 :(得分:0)
声明
<div class="container">
<img src="..." alt="Profile image" class="profileImg">
<div class="overlay">
<i class="fas fa-pencil-alt text"></i>
</div>
</div>
与定义不符
int Power(/* in */int pow,/* in */int x,/* out */int &result);
此外,该定义的末尾有一个int Power(/*in*/int pow,/*in*/int x,/*out*/int result);
,不应在该位置。您可以尝试将其更改为:
;
但是我建议您改用int Power(/*in*/int pow,/*in*/int x,/*out*/int& result)
。
答案 1 :(得分:0)
为什么要传递结果地址?我建议您从函数参数和主作用域中的变量中删除结果变量,这将解决该问题。
int power(int pow,int x);
int main(){
int pow,x;
// Get the pow and number and the index, you wrote it
cout << "Enter power: "; //prompt for integer in for power to be raised by
cin >> pow; //integer in
cout << "Enter value to be raised to power: ";
cin >> x;
cout << Power(pow,x);
// If you want to store the result do
int result = Power(pow,x);
}
int Power(int pow,int x){
int result = 1; //result is set at 1 by default , you want to declare result here
while(pow > 0){
result = result * x;
pow--; }
return result; }
问题是您的定义中包含int &result
,但您将其声明为int result
。上面的代码解决了您的问题,使您不必定义变量结果并将其传递给Power