C ++如何将函数连接到程序?

时间:2013-11-03 17:03:37

标签: c++ function numbers

我是初学者,在C ++中,我想做一个找到3个数字中最大的程序。因为我不能定义在主要部分中找到的函数而不使用类?谢谢你的时间!

#include<iostream>
#include<cmath>
using namespace std;

int maximum(int x, int y, int z);

int main()
{
    int x,y,z;
    int max=y;
    int min=x;

    cout<<"Enter 3 numbers to find out which one is bigger. First: ";
    cin>>x;
    cout<<"Second: ";
    cin>>y;
    cout<<"Third: ";
    cin>>z;
    cout<<"Biggest is: "<<max<<endl;

    cout<<"Earliest time to meet is: "<<max<<endl;

    return 0;
}

//thats the function that checks the biggest number
int maximum (int x, int y, int z)
{
    int max = x;

    if (y > max) {
        max = y;
    }
    if (z > max) {
        max = z;
    }

    return max;
}

3 个答案:

答案 0 :(得分:3)

只需添加call to your function,例如

 max = maximum(x,y,z);

显示之前

 cout<<"Biggest is: "<<max<<endl;

答案 1 :(得分:3)

从main()函数调用最大函数。简单。

#include<iostream>
#include<cmath>
using namespace std;

int maximum(int x, int y, int z);

int main()
{
int x,y,z;

cout<<"Enter 3 numbers to find out which one is bigger. First: ";
cin>>x;
cout<<"Second: ";
cin>>y;
cout<<"Third: ";
cin>>z;
cout<<"Biggest is: "<< maximum (x, y, z) << endl;

return 0;
}

//thats the function that checks the biggest number
int maximum (int x, int y, int z) 
{
int max = x;

if (y > max) {
    max = y;
}
if (z > max) {
    max = z;
}

return max;
}

答案 2 :(得分:0)

#include<iostream>
#include<cmath>
using namespace std;

int maximum(int x, int y, int z);

int main()
{
   int x,y,z;
   // get values x, y, and z from user input
   int max = maximum(x, y, z);
   // ...
}