在main中调用函数 [英] Calling a function in main
问题描述
我正在学习 C ++ ,并且在这里有一些代码:
I'm just learning C++ and I have a little code here:
using namespace std;
int main()
{
cout<<"This program will calculate the weight of any mass on the moon\n";
double moon_g();
}
double moon_g (double a, double b)
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
它可以编译,但是当我运行它时,它只会打印出来:
It compiles, but when I run it it only prints out:
此程序将计算月球上任何质量的重量
但不执行 moon_g
函数。
推荐答案
此行:
double moon_g();
实际上没有做任何事情,它只是说一个函数 double moon_g()
存在。您想要的是这样的东西:
doesn't actually do anything, it just states that a function double moon_g()
exists. What you want is something like this:
double weight = moon_g();
cout << "Weight is " << weight << endl;
这还行不通,因为您没有函数 double moon_g()
,您拥有的是函数 double moon_g(double a,double b)
。但是这些参数并没有真正的用(嗯,是的,但是没有理由将它们作为 arguments 传递)。因此,请像这样从函数中消除它们:
This won't work yet, because you don't have a function double moon_g()
, what you have is a function double moon_g(double a, double b)
. But those arguments aren't really used for anything (well, they are, but there's no reason to have them passed in as arguments). So eliminate them from your function like so:
double moon_g()
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
double a;
cin>>a;
double b=(17*9.8)/100;
double mg=a*b;
return mg;
}
(并在调用函数之前先声明该函数。)可能会有更多的改进,但这已经足够了。
(And declare the function before you call it.) More refinements are possible, but that'll be enough for now.
这篇关于在main中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!