将函数插入主要部分

Inserting a function into main part

本文关键字:函数 插入      更新时间:2023-10-16

我是一个初学者,在将函数调用到程序的主要部分时遇到了一些小问题。

#include <iostream>
#include<cmath>
int getAbsProd(int a, int b)
{
cout<<"Insert integer: "<<endl;
cin>>a;
cout<<"Insert another integer: "<<endl;
cin>>b;
cout<<"The absolute value of the multiplication is: "<<abs(a*b)<<endl;
return abs(a*b);
}

int main()
{
cout<<getAbsProd();
return 0;
}

我正在使用代码块,无法调用math.h,有人建议在某个地方调用cmath。

编辑:

现在我已经阅读了您的代码,似乎不需要在方法getAbsProd中设置参数。删除int ab,使其看起来像这样:

int getAbsProd()

那你该好好走了!

解释:

如果要从main或其他方法调用它,并且需要从main提供它的输入,那么方法中需要包含参数。在您的情况下,您自己并没有从代码中给它任何输入,而是调用cin。因此,您不需要在参数中包含(int a, int b),而是在方法本身中将其创建为局部变量。

int getAbsProd()
{
int a = 0;
int b = 0;
cout<<"Insert integer: "<<endl;
cin>>a;
cout<<"Insert another integer: "<<endl;
cin>>b;
cout<<"The absolute value of the multiplication is: "<<abs(a*b)<<endl;
return abs(a*b);
}

原始帖子:

您需要为这些方法提供计算值所需的参数。例如,您的main方法应该类似于:

int main()
{
cout<<getAbsProd(1, 2); //you need to have an int a, and an int b
return 0;
}

现在,你的函数应该计算1的绝对值(记住,这是你给函数的int a),乘以2(你给函数提供的第二个参数,即int b)。

在这种情况下,您的输出应该是2

有关更多信息,请查看本教程中有关C++中的函数:

http://www.cplusplus.com/doc/tutorial/functions/

希望这能有所帮助。如果还有其他内容,请随时评论:-)

函数getAbsProd需要两个参数:int aint b。你调用它时没有任何参数。例如,要为ab传递5,请这样调用它:

int main()
{
  cout << getAbsProd(5, 5);
  return 0;
}

我尝试了您的代码,发现了错误。

有两种可能的解决方案可以使代码正常工作。

解决方案1:声明不带任何参数的getAbsProd()

并在函数中声明整数a和b

比如

int getAbsProd() {
int a,b;
cout<<"enter value of a";
cin>>a
.
.
return 0;
}

解决方案2:如果您想声明函数接受参数,请向用户索取main中的数字,然后用"a"answers"b"作为参数调用函数

int main () {
int a,b;
cout<<"enter value of a";
cin>>a;
cout<<"enter value of b";
cin>>b;
cout<<getAbsProd(a,b);
return 0;
}

进行这两个更改中的任何一个,您的代码都应该可以工作。

希望能有所帮助,Rakesh Narang