英文:
Signed long to float and then to signed short
问题
这是我的代码:
#include <stdio.h>
typedef signed long int32_t;
typedef signed short int16_t;
int main() {
int32_t var1 = 1200;
int16_t var2;
var2 = (int16_t)((float)var1 / 1000.0);
printf("Hello World: %d", var2); // 打印 1 应该打印 1.2
return 0;
}
在C中进行数据类型转换。因此,我试图将'signed short'类型的'var2'的值获取为1.2,但我得到了1的值。我必须使用16位寄存器,不能使用32位浮点数。
英文:
Here is my code:
#include <stdio.h>
typedef signed long int32_t;
typedef signed short int16_t;
int main() {
int32_t var1 = 1200;
int16_t var2;
var2 = (int16_t)((float)var1/1000.0);
printf("Hello World: %d", var2); // prints 1 should print 1.2
return 0;
}
Typecasting between datatypes in C. As a result, I am trying to get the value of 'var2' as 1.2 in the signed short, but I have got value 1. I have to use the 16bit register and I cannot use 32bit float.
答案1
得分: 1
printf("Hello World: %d", var2); // prints 1 should print 1.2
不应该打印1.2。
(float)var1
转换为float
。(float)var1/1000.0
- 结果为1.2。(int16_t)1.2
- 转换为整数,结果为1
。
顺便说一句,使用 %d
格式无法打印 1.2
。要百分之百正确,应该使用 %hd
格式来打印短整数。
强制类型转换只进行类型之间的转换,而不进行二进制复制。
英文:
> printf("Hello World: %d", var2); // prints 1 should print 1.2
No it should not.
(float)var1 converts
tofloat
.(float)var1/ 1000.0
- result 1.2(int16_t)1.2
- converts to integer and the result is1
BTW you cant print 1.2
using %d
format. To 100% correct you should use %hd
format to print short integer.
Casting does not binary copy only converts between the types
答案2
得分: 1
var2是一个"signed short"类型,它只能包含整数值。如果你将一个小数赋给它,它会截断小数部分(0.2),只保留整数部分(1)。希望我有所帮助。祝你有一个愉快的一天!
英文:
var2 is a "signed short" type and it can only contains integer value. If you assign to it a decimal number it truncate the decimal part (0.2) and retains only the integer part (1). I hope I was helpful. Have a nice day!
答案3
得分: 1
你已经在变量var1中拥有它的16位整数。你的表示被称为“缩放整数”。只需在需要打印值时执行转换。
printf("%f\n", (float)(var1/1000.0));
英文:
You already have it in a 16-bit int in var1. Your representation is called "scaled integer". Just do the conversion when you need to print the value.
printf("%f\n", (float)(var1/1000.0));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论