float batt = ((float)rand()/(float)(RAND_MAX)) * 5.0;
demo_printf("Battery:%.2f\n", batt);
从上面的一行来看,它为一个随机数做了一次。我想问一下如何做到这一点,让它像一个循环逐渐减少一样。也许每0.1。
我无法循环人口印记。我不能 。我只能在elswhere循环
答案 0 :(得分:1)
// obtain initial random float
float batt = ((float)rand()/(float)(RAND_MAX)) * 5.0;
// iterate beginning with this random float downwards by steps of 0.1f
for (float x = batt; x > 0; x -= 0.1) {
demo_printf("Battery:%.2f\n", x);
}
答案 1 :(得分:1)
咦?
这个问题很奇怪。你的意思是这样的:
float batt = 5.f * rand() / RAND_MAX;
while(batt > 0.f)
{
printf("Battery is %.1f\n", batt);
batt -= 0.1f;
}
示例输出:
Battery is 4.2
Battery is 4.1
Battery is 4.0
Battery is 3.9
Battery is 3.8
Battery is 3.7
Battery is 3.6
Battery is 3.5
Battery is 3.4
[ ... more like this ...]
Battery is 1.0
Battery is 0.9
Battery is 0.8
Battery is 0.7
Battery is 0.6
Battery is 0.5
Battery is 0.4
Battery is 0.3
Battery is 0.2
Battery is 0.1
Battery is 0.0
答案 2 :(得分:0)
使用2个变量,目标和当前:
float current = 5.0f;
float target = 2.5f;
while(current > target) {
// print here
current -= 0.1f;
}
current = target;
// final print here
请注意,浮点文字常量0.1f
到二进制浮点数的转换永远不会完全准确,并且递减不会精确到0.1。但要解决这个问题是另一个问题。