使用用户定义的函数查找数字的幂时出现问题

Issue in finding power of a number using user defined functions

本文关键字:问题 数字 查找 用户 定义 函数      更新时间:2023-10-16

我的代码以及输出

以下代码不起作用。它没有错误,我认为在逻辑上犯了一些错误。我想使用函数找到数字的幂。如何使此代码工作?

代码:

#include<iostream>
using namespace std;
int pow(int);
int main()
{
int x,p,ans;
cout<<"Enter a number";
cin>>x;
cout<<"Enter the power of the number";
cin>>p;
ans=pow(x);
cout<<ans;
return 0;
}
int pow(int)
{
int a=1,i,p,x;
for(i=0;i<=p;i++)
{
a=a*x;
}
return a;
}

这是工作代码:

#include<iostream>
using namespace std;
int pow(int, int);
int main()
{
int x,p,ans;
cout<<"Enter a number";
cin>>x;
cout<<"Enter the power of the number";
cin>>p;
ans=pow(x, p);
cout<<ans;
return 0;
}
int pow(int x, int p)
{
int a=1,i;
for(i=0;i<=p;i++)
{
a=a*x;
}
return a;
}

艾德酮

您必须将局部变量传递到函数中,而不是定义具有相同名称的新变量。您正在执行的操作应该为您提供有关未使用变量(xpmain(的警告,并且由于对那里定义的变量的未初始化读取,它还会在pow中调用未定义的行为。

你的功能也错了。你只是将 1 乘以一个值很多次,它永远保持 1。

您的函数必须指定参数名称(而不仅仅是类型(:

int pow(int) -> int pow(int b, int p)

您迭代一次超过必要的次数:

for (i = 0; i <= p; i++) -> for (i = 0; i < p; i++)

您可以缩短一些算术运算:

a=a*x -> a *= x;

最后一个函数:

int pow(int b, int p)
{
int a = 1, i;
for (i = 0; i < p; i++)
a *= b;
return a;
}

您可以通过传递预先声明的变量来调用它:

pow(x, p)

所以你的最终代码是这样的:

#include <iostream>
int pow(int b, int p)
{
int a = 1, i;
for (i = 0; i < p; i++)
a *= b;
return a;
}
int main()
{
int x, p, ans;
std::cin >> x >> p;
ans = pow(x, p);
std::cout << ans << std::endl;
return 0;
}