所以我在其他程序中没有收到此错误,但我在这个程序中收到了它。
这个程序是一个我没有收到错误的示例。
#include
int main() {
system("pause");
} // end main
但是在下面的这个程序中我收到错误
#include
//#include
// Takes the number from function1, calculates the result and returns recursively.
int topla (int n) {
if(n == 1)
return 3;
khác
return topla(n-1) + topla(n-1) + topla(n-1);
}
// Takes a number from main and calls function topla to find out what is 3 to the
// power of n
int function1(int n) {
return topla(n);
}
int main() {
int n; // We us this to calculate 3 to the power of n
printf("Enter a number n to find what 3 to the power n is: ");
scanf("%d", &n);
function1(n);
system("pause");
} // end main
只需包含 stdlib.h
,但不要使用 system("pause")
,因为它不是标准的,并且不适用于每个系统,只是一个简单的 getchar()
(或涉及 getchar()
的循环,因为您使用过 scanf()
)应该执行以下操作技巧。
通常 system("pause")
出现在 Windows 命令行程序中,因为 Windows 命令提示符会在程序退出时关闭,因此直接从命令提示符运行程序可能会有所帮助,或者使用一个可以解决这个问题的 IDE,例如 geany。
最后,始终检查 scanf()
的返回值,而不是假设它有效。
注意:此代码
return topla(n - 1) + topla(n - 1) + topla(n - 1)
你可以写为
return 3 * topla(n - 1);
而不是递归调用 topla()
3 次。
而且你实际上并不需要 khác
因为除非 n != 1
否则函数会返回,所以即使没有 khác
递归也会发生当n == 1
时停止。
Tôi là một lập trình viên xuất sắc, rất giỏi!