may*_*raj 5 c gcc compiler-optimization pow
这是我的阶乘程序——它正在执行并给出正确的结果:
#include <stdio.h>
int main()
{
int n;
printf("enter the no=");
scanf("%d", &n);
fun(n);
printf("%d\n", fun(n));
return 0;
}
int fun(int n)
{
if(n == 0)
return 1;
else
return fun(n - 1) * n;
}
Run Code Online (Sandbox Code Playgroud)
这是我计算一个数的幂的程序——这给出了 0 而不是正确的结果,但几乎相同:
#include <stdio.h>
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
pow(m, n);
printf("%d\n", pow(m, n));
return 0;
}
int pow(int m, int n)
{
if(n == 0)
return 1;
else
return pow(m, n - 1) * m;
}
Run Code Online (Sandbox Code Playgroud)
两者都运行在同一个编译器上。
为什么我的阶乘程序有效,但我几乎相同的幂程序无效?
这里存在一些问题。首先,在第一次调用函数之前,您没有为其声明原型。要做到这一点,你需要的地方int pow(int, int);上面main。这让编译器确切地知道您的函数期望什么以及它返回什么。
通常,这不会导致您看到的行为(尽管这是不好的做法),但是powC 库中已经有一个名为的函数。因为你从来没有给它一个你自己的定义,它被隐式地包含在你的代码中。现在,它期待你投入两个双打并得到一个双打。
在顶部添加原型并重命名您的函数,您将同时解决这两个问题。
(此外,就其价值而言,您接到了一个不必要的电话。)
#include <stdio.h>
int powr(int, int); // helps avoid compiler warnings
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
powr(m, n); // unnecessary
printf("%d\n", powr(m, n));
return 0;
}
int powr(int m, int n)
{
if(n == 0)
return 1;
else
return powr(m, n - 1) * m;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |