简体   繁体   中英

pascal to c++: trunc

I have old pascal code

var i : longint;
    m : double;
begin
  .....
  i := trunc(m);

I have to convert it to C++ code.

An obvious thing here is to write

double m;
int i;
.....
i = static_cast<int>(std::trunc(m));

But the problem here is than pascal's trunc returns integer

function trunc(
  d: ValReal
):Int64;

while c++'s trunc returns double. Is it possible that for example trunc(2.3) will return 1.999999999999 and static_cast will make it 1 instead of 2? If yes is it correct to use static_cast without trunc to get same pascal's behavior?

i = static_cast<int>(m);

When you convert a floating-point value to an integer value in C++, the floating-point value is truncated automatically.

Take a look at the following simple example:

#include <iostream>

int main()
{
    double d = 12.98;
    int i = d;

    std::cout << "i = " << i << '\n';
}

The above program will print

i = 12

Conversions like these are done implicitly by the compiler. For more information please read about implicit conversions (specifically read about floating-integral conversions ).

However, it's important to note (from the linked reference):

If the value cannot fit into the destination type, the behavior is undefined

So the floating point value, after truncation, must fit into the integer type on the left-hand side of the assignment.

All integers (and most longs?) are exactly representable in double . A function like trunc that's defined to return an integer in mathematical sense will never return something that's not an exact integer if its proper return value can be represented in double .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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