c - 浮动总是四舍五入吗?
问题描述
这是我的程序,它将十进制转换为基数-“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]);
}
解决方案
当你除以input
时n
,你正在做整数除法:
input /= n;
整数除法有一个整数结果。无论哪种方式,您都将结果存储回一个整数,因此任何小数部分都会被丢弃。
因此,input
每次循环中存储的值将是20
, 10
, 5
, 2
( not 2.5
), 1
, and 0
。
推荐阅读
- python - 当有人通过回调 url 将内容发回给我时,我如何重定向到另一个页面
- r - 如何在ggplot的直方图条上打印频率
- git-lfs - LFS 未跟踪的文件上的“git lfs lock”应该做什么?
- regex - 正则表达式检查一个数字是否在字符串中重复
- vb.net - DateTimePicker 的 MonthCalendar 的日期未更新
- salt-stack - 您可以使用映射文件而不是 Pillar 将参数传递给 SaltStack 公式吗?
- c++ - 在 Visual Studio Code 中使用 CMake 设置调试模式时出错
- html - 为什么 HTML Video 标签在 ios 设备上不起作用?
- c - 在 c 中定义结构
- python - 当订单很重要(并将每个结果分配给唯一的键)时,迭代多个结果的最简洁方法是什么?