首页 > 解决方案 > 具有多种返回可能性的除法函数

问题描述

我正在做一项学校作业,但我遇到了一个问题。

问题如下:

“编写一个名为 divideIt 的函数,它接受两个整数,将它们相除,并将结果作为浮点数返回。当遇到不可接受的值时,让这个函数跳过除法,并保留小数。你知道要退出什么吗?”

使用我目前拥有的代码,它会像问题状态一样划分并保留小数,但我不明白如何跳过除法。如果我因为不可接受的值而跳过除法,我该怎么做?我应该只使用null吗?另外,我不确定“你知道要放弃什么吗?” 线。

我的代码:

#include <iostream>


using std::cout;
using std::cin;
using std::endl;


//Prototype

float divideIt(int num1, int num2);

int main()
{
    int num1, num2;
    float finalResult;
    finalResult = divideIt(num1, num2);
    cout << "Result: " << finalResult << endl;
}

//Header

float divideIt(int num1, int num2)
{
    cout << "Simple Division\n" << "Input first integer: ";
    cin >> num1;
    cout << "Input second integer: ";
    cin >> num2;
    if(num2 == 0) //I wanted to make ASCII values unacceptable, but because they automatically translated into zeros, so I used that to my advantage on num2.
    {
        cout << "The second value was undefined or unacceptable." << endl;
    }
    return static_cast<float>(num1) / num2;
}

标签: c++c++11

解决方案


如果我因为不可接受的值而跳过除法,我该怎么做?

您可以返回std::nanf('不是数字'):

if (num2 == 0)
    return std::nanf ("");

还有相应的std::isnan功能。

另外,我不确定“你知道要放弃什么吗?” 线。

据推测,它们的意思是“你测试什么来决定一个值是不可接受的”。我认为我们就是这样做的。


推荐阅读