“未定义的”变量和参数

我是一名学生,我正在编写我的第一个函数,所以我确信这对我来说显然是错误的。 在第13行,我在参数中遇到错误,告诉我未定义num1和num2。据我了解传递参数,第9行应该告诉第13行num1和num2是什么(1和2)。既然它不起作用,我显然会误会它的工作原理。

如果有人可以解释我在做什么错,我将不胜感激。谢谢你!

#include <iostream>
#include <string>

using namespace std;


int main()
{
    Subtract(1,2);
    return 0;
}

int Subtract(num1,num2) //num1 and num2 are undefined. 
{
    int num1;
    int num2;
    int x;
    x = num1 - num2;
    cout << x << "/n";
    return 0;

}

zhengbanririye 回答:“未定义的”变量和参数

让我告诉您代码中的问题。

  1. 您需要告诉编译器num1和num2是什么。
  2. 您的代码还有另一个严重的问题。您必须知道,大多数情况下,编译器在编译过程中会逐行进行。因此,当他到达您的主要位置时,他不知道什么是减法。您应该告诉他这是一个函数,否则将是编译时错误。提示-尝试定义您在代码中编写的每个变量。编译器自己无法推断任何内容。
  3. 正如评论中提到的那样,我发现了另一个问题,要移至下一行,您应该输入“ \ n”(反斜杠)。

int Subtract(int,int); // This is must before main if you defined subtract later.
int main()
{
    Subtract(1,2); // Compiler don't know what is subtract. As you defined Subtract later. The compiler doesn't know what is Subtract. To overcome this you need to declare a function before main.
    return 0;
}

int Subtract(int num1,int num2) // Here you need to tell that they are an integer. 
{
 //   int num1;
 ///   int num2; // once you told that num1 and num2 are an integer no need to do this. If you will try this. It will be a compile time error. As you already made num1 and num2 variable above. So can't declare variable twice.
    int x;
    x = num1 - num2;
    cout << x << "/n";
    return 0;

}
,

Num1和num2没有定义,函数in将屏蔽另一个。

本文链接:https://www.f2er.com/3169244.html

大家都在问