c-如何修复用Xcode编写的代码?在主函数中,Xcode显示错误:此处不允许函数定义


#include <stdio.h>
int f(int x, int y) {
for (int i = 10; i > 5; i--) {
if (x % i == 0) {
y = x ^ 3;
printf("x is %d and y is %dn", x, y);
return x + y;
}
else {
y = x + 1;
printf("x is %d and y is %dn", x, y);
return x * y;
}
}
int main() { // I am getting error on this line.Function definition is not
// allowed here.
int a = f(30, 10);
int b = f(20, 5);
return 0;
}
}

Xcode将其显示为解析问题。请帮我修复这个代码。

您错过了一个}以结束函数f()。因此,您错误地将main()放置在函数f()中。

代码中的问题是,

  1. 此处缺少int f(int x, int y)的右大括号}。请检查代码内部的注释
  2. 在您的程序末尾再添加一个不需要的大括号}

纠正后的代码为

#include <stdio.h>
int f(int x, int y) {
for (int i = 10; i > 5; i--) {
if (x % i == 0) {
y = x ^ 3;
printf("x is %d and y is %dn", x, y);
return x + y;
} //Closing brace of 'if' condition
else {
y = x + 1;
printf("x is %d and y is %dn", x, y);
return x * y;
} //Closing brace of 'else' condition
} //Closing brace of for-loop
} //Here add the closing brace of 'int f(int x, inty)'
int main() {
int a = f(30, 10);
int b = f(20, 5);
return 0;
} //Removed the last '}' in your code

最新更新