Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用用户定义函数查找数字幂的问题_C++ - Fatal编程技术网

C++ 使用用户定义函数查找数字幂的问题

C++ 使用用户定义函数查找数字幂的问题,c++,C++,以下代码不起作用。它没有错误,我认为我在逻辑上犯了一些错误。我想用函数求一个数的幂。如何使此代码工作 守则: #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";

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

守则:

#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;
}
#包括
使用名称空间std;
int-pow(int);
int main()
{
int x,p,ans;
coutx;
coutp;
ans=功率(x);
cout以下是工作代码:

#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;
}
#包括
使用名称空间std;
int-pow(int,int);
int main()
{
int x,p,ans;
coutx;
coutp;
ans=功率(x,p);

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

intpow(int)->intpow(intb,intp)

您需要多次迭代:

for (i = 0; i <= p; i++) -> for (i = 0; i < p; i++)
最后一项职能:

int pow(int b, int p)
{
    int a = 1, i;
    for (i = 0; i < p; i++)
        a *= b;
    return a;
}
因此,您的最终代码如下所示:

#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;
}
#包括
内部功率(内部b,内部p)
{
int a=1,i;
对于(i=0;i>x>>p;
ans=功率(x,p);

std::难道你至少应该能够给出输入、预期输出和实际输出的示例吗。@ChiefTwoPencils我已经附上了图片。请用调试会话的结果编辑你的帖子。通常,使用调试器比发布到StackOverflow并等待回复快得多。请重命名你的函数,这样它就不会冲突与。虽然从技术上讲不是,因为您的函数使用整数。@ThomasMatthews很抱歉。正如我所说,我是一个完全的初学者。我甚至不知道调试是什么,将阅读有关它的内容,谢谢。最后,应该更改函数的名称,以避免与冲突。事实上,变量可以有更好的命名,并且可以使用“I”变量在for循环内声明。此外,“ans”变量也可以很容易地忽略。
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;
}