我刚刚学习C++,我在这里有一些代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它编译,但当我运行它只打印出来:
This program will calculate the weight of any mass on the moon
但不执行该moon_g功能.
这一行:
double moon_g();
Run Code Online (Sandbox Code Playgroud)
它实际上没有做任何事情,它只是说double moon_g()存在一个函数.你想要的是这样的:
double weight = moon_g();
cout << "Weight is " << weight << endl;
Run Code Online (Sandbox Code Playgroud)
这还行不通,因为你没有函数double moon_g(),你拥有的是一个函数double moon_g(double a, double b).但是那些参数并没有真正用于任何事情(好吧,它们是,但是没有理由让它们作为参数传入).所以从你的函数中消除它们是这样的:
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;
}
Run Code Online (Sandbox Code Playgroud)
(并在调用之前声明该函数.)可以进行更多细化,但现在已经足够了.