在 main 中调用函数

Calling a function in main(在 main 中调用函数)
本文介绍了在 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
";

    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).但是这些参数并没有真正用于任何事情(好吧,它们是,但没有理由将它们作为参数传入).所以像这样从你的函数中消除它们:

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 中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why does C++ compilation take so long?(为什么 C++ 编译需要这么长时间?)
Why is my program slow when looping over exactly 8192 elements?(为什么我的程序在循环 8192 个元素时很慢?)
C++ performance challenge: integer to std::string conversion(C++ 性能挑战:整数到 std::string 的转换)
Fast textfile reading in c++(在 C++ 中快速读取文本文件)
Is it better to use std::memcpy() or std::copy() in terms to performance?(就性能而言,使用 std::memcpy() 或 std::copy() 更好吗?)
Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation?(C++ 标准是否要求 iostreams 性能不佳,或者我只是在处理一个糟糕的实现?)