没有上限或下限的 C++ 舍入数
C++ Rounding Numbers without ceiling or floor
我正在尝试回答 DS Malik 的 C++ 编程:从问题分析到程序设计
中的以下问题
第 2 章,第 7 题
Write a program that prompts the user to input a decimal number and
outputs the number rounded to the nearest integer.
我目前的计划
#include <iostream>
using namespace std:cout;
using namespace std:cin;
int main()
{
double decimalNum;
cout << "Please enter a decimal number: ";
cin >> decimalNum;
return 0;
}
是否可以在不使用下限或上限的情况下将数字四舍五入为整数?请注意,我几天前才开始 C++ 编程,所以请不要太复杂。
加 0.5 然后调用 modf
may be your best bet - the integral part is returned as a double
so you still get correct results for numbers outside the range of even a 64-bit integral type. There are a lot of other options also available in the cmath header.
正如评论中指出的那样,添加 0.5
并将其类型转换为 int
.
添加 0.5
的原因是为了确保数字四舍五入而不是小数部分被截断。因此,6.6
将被截断为 6
,但四舍五入为 7
。
类型转换是改变类型的过程。有些类型彼此兼容,但又有所不同。例如int
、float
、double
、long
都代表数字。所以当你写一个int + float
时,编译器会先自动将int
转换成float
,然后再进行运算。这称为类型转换。你可以明确地做,或者编译器做很多次。
所以,总而言之,添加 0.5
将帮助您正确四舍五入,而类型转换将改变类型。
您可以试试下面的代码 -
#include <iostream>
using namespace std;
int main()
{
double decimalNum;
cout << "Please enter a decimal number: ";
cin >> decimalNum;
int roundNum = decimalNum + 0.5;
cout << "The nearest rounded number : " << roundNum << endl;
return 0;
}
我正在尝试回答 DS Malik 的 C++ 编程:从问题分析到程序设计
中的以下问题第 2 章,第 7 题
Write a program that prompts the user to input a decimal number and outputs the number rounded to the nearest integer.
我目前的计划
#include <iostream>
using namespace std:cout;
using namespace std:cin;
int main()
{
double decimalNum;
cout << "Please enter a decimal number: ";
cin >> decimalNum;
return 0;
}
是否可以在不使用下限或上限的情况下将数字四舍五入为整数?请注意,我几天前才开始 C++ 编程,所以请不要太复杂。
加 0.5 然后调用 modf
may be your best bet - the integral part is returned as a double
so you still get correct results for numbers outside the range of even a 64-bit integral type. There are a lot of other options also available in the cmath header.
正如评论中指出的那样,添加 0.5
并将其类型转换为 int
.
添加 0.5
的原因是为了确保数字四舍五入而不是小数部分被截断。因此,6.6
将被截断为 6
,但四舍五入为 7
。
类型转换是改变类型的过程。有些类型彼此兼容,但又有所不同。例如int
、float
、double
、long
都代表数字。所以当你写一个int + float
时,编译器会先自动将int
转换成float
,然后再进行运算。这称为类型转换。你可以明确地做,或者编译器做很多次。
所以,总而言之,添加 0.5
将帮助您正确四舍五入,而类型转换将改变类型。
您可以试试下面的代码 -
#include <iostream>
using namespace std;
int main()
{
double decimalNum;
cout << "Please enter a decimal number: ";
cin >> decimalNum;
int roundNum = decimalNum + 0.5;
cout << "The nearest rounded number : " << roundNum << endl;
return 0;
}