简体   繁体   English

没有上限或下限的C ++舍入数字

[英]C++ Rounding Numbers without ceiling or floor

I'm attempting the following question from DS Malik's C++ Programming: From Problem Analysis to Program Design 我正在尝试DS Malik的C ++编程中的以下问题:从问题分析到程序设计

Chapter 2, Question 7 第2章,问题7

Write a program that prompts the user to input a decimal number and outputs the number rounded to the nearest integer. 编写一个程序,提示用户输入一个十进制数字,并输出四舍五入到最接近的整数的数字。

My program so far 到目前为止我的程序

 #include <iostream>

 using namespace std:cout;
 using namespace std:cin;

 int main()
  {
    double decimalNum;
    cout << "Please enter a decimal number: ";
    cin >> decimalNum;
    return 0;
  }

Is it possible to round the number to an integer without using floor or ceiling? 是否可以将数字四舍五入为整数而无需使用底数或上限? Please note that I just started C++ programming a few days ago so nothing too overly complex please. 请注意,我几天前才刚刚开始C ++编程,所以请不要太复杂。

As pointed out in the comments, add 0.5 and typecast it to as int . 如注释中所指出的,添加0.5并将其类型转换为int

The reason behind adding 0.5 is to ensure that numbers are rounded off as opposed to the decimal part being truncated. 添加0.5的原因是为了确保四舍五入,而不是舍去小数部分。 So, 6.6 will be truncated to 6 , but rounded off to 7 . 因此, 6.6将被截断为6 ,但四舍五入为7

Typecasting is the procedure of changing types. 类型转换是更改类型的过程。 Some types are compatible with each other, but are different. 某些类型彼此兼容,但有所不同。 For example, int , float , double , long all represent numbers. 例如, intfloatdoublelong都表示数字。 So when you write an int + float , the compiler first converts the int to a float automatically, and then does the operation. 因此,当您编写int + float ,编译器首先将int自动转换为float ,然后执行操作。 This is known as typecasting. 这称为类型转换。 You can do it explicitly, or the compiler does it many times. 您可以明确地执行此操作,或者编译器可以多次执行。

So, to wrap it up, adding 0.5 will help you round off correctly, and typecasting will change the type. 因此,总结起来,添加0.5将帮助您正确舍入,并且类型转换将更改类型。

You can try the following code - 您可以尝试以下代码-

#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;
}

Adding 0.5 then calling 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. 加0.5然后调用modf可能是最好的选择-整数部分将作为double精度返回,因此即使对于64位整数类型范围之外的数字,您仍然可以获得正确的结果。 There are a lot of other options also available in the cmath header . cmath标头中还有许多其他选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM