簡體   English   中英

如何修復用 Xcode 編寫的這段代碼? 在主函數中,Xcode 顯示錯誤:此處不允許定義函數

[英]How to fix this code written in Xcode? In the main function, Xcode is displaying the error:Function definition is not allowed here

#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 %d\n", x, y);
      return x + y;
    }

    else {

      y = x + 1;
      printf("x is %d and y is %d\n", 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 %d\n", x, y);
      return x + y;
    } //Closing brace of 'if' condition
    else {

      y = x + 1;
      printf("x is %d and y is %d\n", 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM