c++ - 具有多种返回可能性的除法函数
问题描述
我正在做一项学校作业,但我遇到了一个问题。
问题如下:
“编写一个名为 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
功能。
另外,我不确定“你知道要放弃什么吗?” 线。
据推测,它们的意思是“你测试什么来决定一个值是不可接受的”。我认为我们就是这样做的。
推荐阅读
- excel - Excel VBA CMD 列出目录内容
- pdf - 如何使用 Ghostscript mswinpr2 使用打印驱动程序的设置创建 postscript
- c - “__u8 b[16]”与“无符号字符 uuid_t[16]”
- c# - CSVHelper 如何将字符串映射到对象
- swift - 从可填写的pdf swift中提取数据
- azure - 将 SparkConf 设置从命令行传递给 Spark
- reactjs - React 提取类型/标签并将值传递给子级
- python-3.x - 尝试,除了和记录 Python
- actionscript-3 - AS 3 动作脚本
- docker - 获取使用 Docker Swarm 跨主机部署的微服务的指标