简体   繁体   English

帕斯卡转C ++:截断

[英]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. 我必须将其转换为C ++代码。

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 但是这里的问题是帕斯卡的trunc返回整数

function trunc(
  d: ValReal
):Int64;

while c++'s trunc returns double. 而c ++的trunc返回double。 Is it possible that for example trunc(2.3) will return 1.999999999999 and static_cast will make it 1 instead of 2? 例如trunc(2.3)是否可能返回1.999999999999而static_cast将其设置为1而不是2? If yes is it correct to use static_cast without trunc to get same pascal's behavior? 如果是,使用不带有trunc的static_cast获得相同的pascal行为是否正确?

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. 在C ++中将浮点值转换为整数值时,浮点值会自动被截断。

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 . 所有整数(和最长整数?)都可以用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 . 如果trunc之类的函数定义为在数学意义上返回整数,则如果它的正确返回值可以用double表示,则永远不会返回不是精确整数的东西。

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

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