首页 > 解决方案 > 浮动总是四舍五入吗?

问题描述

这是我的程序,它将十进制转换为基数-“n”,您可以将数字以“n”为基数输入您想要转换的数字,它运行成功但我有一个问题,我不明白为什么if ((float)input / (float)n <= 0)可以通过在第五次。我正在用 vscode 调试并观察每个断点和步骤的值,这是结果

(运行此行if ((float)input / (float)n <= 0)

输入=20,n=2

第一次:20/2=10(通过)

第二次:10/2=5(通过)

第三次:5/2=2.5(通过)

第四次:2.5/2=1(通过)我不明白为什么它是“1”而不是“1.25”(我认为这是我的主要问题,浮动总是绕行吗?)

第五次:1/2=0.5(通过)

第六次:0.5/2=0(失败和中断)

希望有人能解释一下,我会很感激,英语不是我的母语,所以请原谅我。

#include <stdio.h>
#include <stdlib.h>

void rev(int num[]);

int cnt = 0;

int main()
{

int input = 20, num[10], i, n = 2;

// Decimal turn to base-n

printf("Decimal \"%d\" to base-%d = ", input, n);

for (i = 0; i < 10;)
{
    if ((float)input / (float)n <= 0)
        break;
    else
    {
        num[i] = input % n;
        input /= n;
        i++;
        cnt++;
    }
}
rev(num);

printf("\n");

system("pause");
return 0;
}

void rev(int num[])
{
int i;

i = cnt - 1;

for (i; i >= 0; i--)
    printf("%d", num[i]);
}

标签: c

解决方案


当你除以inputn,你正在做整数除法:

input /= n;

整数除法有一个整数结果。无论哪种方式,您都将结果存储回一个整数,因此任何小数部分都会被丢弃。

因此,input每次循环中存储的值将是20, 10, 5, 2( not 2.5 ), 1, and 0


推荐阅读