这就是问题所在:Totals 游戏可以由任意数量的人玩。它从总数 100 开始,每个玩家轮流对该总数进行 -20 到 20 之间的整数位移。获胜者是通过调整使总数等于 5 的玩家。仅使用给定的三个变量: 全部的 调整 柜台 这是我到目前为止所拥有的:
#include <stdio.h>
int main (void)
{
int counter=0;
float adj;
int ttl=100;
printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");
while (ttl!=5)
{
printf("YOUR ADJUSTMENT?");
scanf("%f",&adj);
counter++;
if (adj<=20 && adj>=-20)
{
ttl=ttl+adj;
printf("The total is %d\n",ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
printf("The game is won in %d steps!",counter);
}
我需要: 当输入十进制数时,它会转到其他地方。如何确定 float 是否有小数部分。
最佳答案
您可以将 float
转换为 int
,然后将其与您的原始变量进行比较。如果它们相同,则没有小数部分。
通过使用这种方法,不需要临时变量或函数调用。
float adj;
....
if (adj == (int)adj)
printf ("no fractional!\n");
else
printf ("fractional!\n");
解释
由于 int
无法处理小数,因此 float
的值将被截断为 int
(例如 (float )14.3
将被截断为 (int)14
)。
当比较 14
和 14.3
时,很明显它们不是相同的值,因此是“分数”!将被打印出来。
关于c - 确定 float 是否有小数部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549365/