Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c++ - Calling a function in main

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
";

    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:

This program will calculate the weight of any mass on the moon

but doesn't execute the moon_g function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This line:

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...