c++ - 如何将 double 转换为 unsigned char?

标签 c++ casting type-conversion double unsigned-char

我正在寻找使用 C++ 将 double vector 更改为无符号字符。 为了确保它有效,我写道:

unsigned char x = 0;
double y = 4.6;
x = (unsigned char) y;
printf("%d", y);
cout << endl << "the char of 4.6 is: " << x;
getchar();

但不是 char 等于 4 或 5 我得到一个巨大的数字,如 1717986918 或带有 cout 的菱形符号。

我认为这是因为它将 4.6 解释为“4.6”,但有没有办法保存它,使其变成一个接近相等值的无符号字符?

最佳答案

diamond symbol with cout

(unsigned char)4.6被截断为 4 .

但是当你cout一个char它打印相应的字符(例如 cout << char(65) 将打印 A )。如果你想打印你的 char那么您需要先将其转换为更宽的整数类型,例如:

double y = 4.6;
char x = y;     // x == 4
cout << (int)x; // prints "4"
//      ^^^^^

I get a huge number like 1717986918

问题出在你的printf上,与您提供的参数(%d = signed integer)相比,您使用了错误的格式说明符(char)。但是您已经知道了,我只是在完善我的答案。 ;)

同样,您可能想先施放它:

printf("%d", (int)x);

关于c++ - 如何将 double 转换为 unsigned char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665918/

相关文章:

c++ - Gstreamer appsrc : odd behaviour of need-data callback

c++ - 凭据提供程序的自定义 GUI

c - 在 C 中转换指针的规则是什么?

sql - 无法在 presto 中将 '' 转换为 bigint

php: is_numeric 对前导空格和尾随空格的处理方式不同

python - 如何在 python3 中将 OrderedDict 转换为常规字典

c++ - 使用 bool operator== 比较对象

c++ - 检测和打印无向图中的循环

sql - 如何将字符串与整数进行比较

python - 在 Python 中将 int 赋值给变量是什么意思?