给定 n,程序应计算 1^1 + 2^2 + 3^3 + ... 直到 n-1^n-1。下面是我的代码,其中 while 循环中有一个函数,并且传递的值来自函数中的 n-1 。函数定义有两个返回 ans 的变量。输出总是错误1。
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
int la, ans;
if(y==0)
return 1;
else
la= (x*power(x, y-1));
ans+=la;
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, a, b, res, res1;
scanf("%d%d", &n, &m);
while(n-- && n>0)
{
a = power(n-1, n-1);
}
printf("%d", a);
}
return 0;
}
最佳答案
您的代码中存在一些问题。
正如另一个答案中所指出的,您的
power
功能已损坏:ans
未初始化{
}
在else
之后丢失
在
while
中,你计算了x^x
,但是你忘记了结果,而你 应该总结一下。在
while
循环中做的第一件事是减少n
并计算power(n-1, n-1)
这听起来不合逻辑。
因此,您更正后的代码可能是:
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
if(y==0)
return 1;
else
return x*power(x, y-1);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, b, a = 0;
scanf("%d%d", &n, &m);
while(n>1)
{
--n;
b = power(n, n);
a += b;
printf("%d^%d -> %3d\n",n, n, b);
}
printf("sum= %d", a);
}
return 0;
}
n = 6 时给出:
5^5 -> 3125
4^4 -> 256
3^3 -> 27
2^2 -> 4
1^1 -> 1
sum=3413
关于计算直到n-1为止的所有数字的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52533290/