C 浮点到整数类型的转换

新手上路,请多包涵

在 C++ 中将浮点类型的数据转换为整数有哪些不同的技术?

 #include <iostream>

using namespace std;
struct database {
  int id, age;
  float salary;
};

int main() {
  struct database employee;
  employee.id = 1;
  employee.age = 23;
  employee.salary = 45678.90;
  /*
     How can i print this value as an integer
     (with out changing the salary data type in the declaration part) ?
   */
  cout << endl << employee.id << endl << employee.
  age << endl << employee.salary << endl;
  return 0;
}

原文由 moala 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 576
1 个回答

如果您不能使用浮点运算,这是将 IEEE 754 浮点数转换为 32 位整数的一种方法。它还具有缩放功能,可以在结果中包含更多数字。缩放器的有用值为 1、10 和 100。

 #define EXPONENT_LENGTH 8
#define MANTISSA_LENGTH 23
// to convert float to int without floating point operations
int ownFloatToInt(int floatBits, int scaler) {
    int sign = (floatBits >> (EXPONENT_LENGTH + MANTISSA_LENGTH)) & 1;
    int exponent = (floatBits >> MANTISSA_LENGTH) & ((1 << EXPONENT_LENGTH) - 1);
    int mantissa = (floatBits & ((1 << MANTISSA_LENGTH) - 1)) | (1 << MANTISSA_LENGTH);
    int result = mantissa * scaler; // possible overflow
    exponent -= ((1 << (EXPONENT_LENGTH - 1)) - 1); // exponent bias
    exponent -= MANTISSA_LENGTH; // modify exponent for shifting the mantissa
    if (exponent <= -(int)sizeof(result) * 8) {
        return 0; // underflow
    }
    if (exponent > 0) {
        result <<= exponent; // possible overflow
    } else {
        result >>= -exponent;
    }
    if (sign) result = -result; // handle sign
    return result;
}

原文由 Harri Luoma 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题