gpt4 book ai didi

c - “系统”未在此范围内声明错误

转载 作者:行者123 更新时间:2023-11-30 18:24:55 28 4
gpt4 key购买 nike

所以我在其他程序中没有收到此错误,但我在这个程序中收到了它。

这个程序是一个我没有收到错误的示例。

#include<stdio.h>

int main() {



system("pause");
} // end main

但是在下面的这个程序中我收到错误

#include <stdio.h>
//#include <stdlib.h>

// Takes the number from function1, calculates the result and returns recursively.
int topla (int n) {
if(n == 1)
return 3;
else
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 次。

而且你实际上并不需要 else 因为除非 n != 1 否则函数会返回,所以即使没有 else 递归也会发生当n == 1时停止。

关于c - “系统”未在此范围内声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580457/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com