具有多重返回可能性的除法函数

问题描述

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

问题如下:

"写一个叫做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;
}

解决方法

如果我因为一个不可接受的值而跳过除法,我应该用什么作为回报?

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

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

还有一个对应的std::isnan函数。

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

据推测,它们的意思是“您通过什么测试来确定某个值是不可接受的”。我认为我们就是这样做的。