"undefined"变量和参数

"undefined" variables and arguments

本文关键字:参数 变量 undefined      更新时间:2023-10-16

我是一名编写第一个函数的学生,所以我相信这将是我的一个明显错误。在第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;
}

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

  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未定义,函数中的一个将屏蔽另一个。