【问题标题】:C++ Using if/else statements in function definition to return smallest numberC++ 在函数定义中使用 if/else 语句返回最小数字
【发布时间】:2018-02-26 10:06:17
【问题描述】:

对于我在 C++ 中的家庭作业,我的目标是编写一个程序,输入三个整数并将它们传递给一个返回最小数字的函数。这只是我学习 C++ 的第 3 周,所以我不太了解。

此外,我只能以#include<iostream>using namespace std 开头。我已经在这几个小时了,这对我来说并不容易。我尝试了很多不同的东西,但我只是得到了错误......

这是到目前为止我真正理解的代码:

#include <iostream>
using namespace std;

int fsmallestNumber(int);

int main() {
    int numberOne;
    int numberTwo;
    int numberThree;
    int smallestNumber;

    cout << "Enter in 3 numbers and I will find the smallest of all three" << endl;
    cin >> numberOne >> numberTwo >> numberThree;


    cout << "The smallest of all three numbers is " << smallestNumber << endl;

}

int fsmallestNumber(int sn){


}

我很困惑如何使用 if/else 语句来找到最小的数字,以及如何将最小的数字返回到函数中以打印出来。

【问题讨论】:

  • 你试过什么?这里似乎没有任何代码试图解决它。您具体需要哪些方面的帮助?
  • See this link 获取大量有用的信息来解释“如何使用 if/else 语句”。

标签: c++ algorithm if-statement min


【解决方案1】:

你来了。

#include <iostream>

using namespace std;

int fsmallestNumber( int, int, int );

int main() 
{
    int numberOne;
    int numberTwo;
    int numberThree;
    int smallestNumber;

    cout << "Enter in 3 numbers and I will find the smallest of all three" << endl;
    cin >> numberOne >> numberTwo >> numberThree;

    smallestNumber = fsmallestNumber( numberOne, numberTwo, numberThree );

    cout << "The smallest of all three numbers is " << smallestNumber << endl;
}

int fsmallestNumber( int x, int y, int z )
{
    int smallest = x;

    if ( y < smallest ) smallest = y;
    if ( z < smallest ) smallest = z;

    return smallest;
}

函数必须接受三个参数。所以必须用三个参数声明。

如果你需要包含一个 else 语句,那么函数可以写成这样

int fsmallestNumber( int x, int y, int z )
{
    int smallest;

    if ( not ( y < x || z < x ) )
    {
        smallest = x;
    }
    else if ( not ( z < y ) )
    {
        smallest = y;
    }
    else
    {
        smallest = z;
    }

    return smallest;
}

请注意,C++ 标准库已经在标头&lt;algorithm&gt; 中声明了合适的算法std::min。所以你可以写

#include <algorithm>

//...

smallestNumber = std::min( { numberOne, numberTwo, numberThree } );

【讨论】:

  • @Maxine 这样的东西可以用 Google 搜索或使用 Stack Overflow 搜索功能找到。这是“c++ 函数参数”的第一个 Google 结果:cplusplus.com/doc/tutorial/functions
猜你喜欢
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2021-08-31
  • 2017-04-12
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多