简体   繁体   English

C:从 int 转换为 float 或 double 时出错

[英]C: Error converting from int to float or double

I'm trying to generate a random number between 1 and 0 for a school project.我正在尝试为学校项目生成一个介于 1 和 0 之间的随机数。 Several places say this should be done using rand() and casting to float.有几个地方说这应该使用 rand() 并强制转换为浮动来完成。 Something like the following:类似于以下内容:

float x = ((float)rand()/(float)(RAND_MAX)) * a;

However, I discovered that whenever I cast from int to float the number is incorrect.但是,我发现每当我从 int 转换为 float 时,数字都是不正确的。 This issue is causing me to get incorrect answers using the code above这个问题导致我使用上面的代码得到不正确的答案

Code:代码:

int rotlat = rand() % 1000;
double newrot = (double) rotlat;
printf("rotational latency: %d\n", rotlat);
printf("new rotational latency: %d\n", newrot);

Output: Output:

rotational latency: 533
new rotational latency: -1841876320

rotational latency: 279
new rotational latency: -1841876320

rotational latency: 148
new rotational latency: -1841876320

rotational latency: 167
new rotational latency: -1841876320

Try:尝试:

printf("new rotational latency: %g\n", newrot); //%g

The %d directive is for decimal integers, not doubles. %d指令用于十进制整数,而不是双精度数。

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

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