将函数插入主要部分
Inserting a function into main part
我是一个初学者,在将函数调用到程序的主要部分时遇到了一些小问题。
#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 a
和b
,使其看起来像这样:
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 a
和int b
。你调用它时没有任何参数。例如,要为a
和b
传递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
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 为 std::vector 编写自定义插入函数
- 类数组插入函数
- 无法在构造函数中执行设置元素插入
- 需要帮助将字符串插入函数
- 尝试使用 EvtSetChannelConfigProperty() 函数更新最大事件日志文件大小时插入的错误值
- 通过构造函数插入 std::map
- 在 C++ 中为特定哈希表创建插入函数
- sqlite3 c 函数:插入语句作为参数时未执行
- 编译器可以将静态模板函数插入
- SegFault将插入std :: vector的成员函数插入std :: vector
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 如何将变量类型作为参数函数插入
- 插入迭代器与容器的成员函数插入器
- 将函数插入主要部分
- 递归函数插入二叉搜索树无法按根访问节点
- 使用自定义哈希函数插入到一个无序集合中
- 如何使用std库函数插入std::列表并保持顺序