浮动整数铸造? [英] Float To Integer Casting?

查看:172
本文介绍了浮动整数铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道浮点数不能完全代表每个数字,所以有些错误肯定会发生。

但最近我遇到了一个问题,我没有得到解释的权利。



请逐步解释转换如何影响输出。



小数位数是如何截去的错误的答案?

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

int main()
{
int x;
int y = 0;
int n = 0;

printf(输入你想要的八进制数等于:);

scanf(%d,& x); (x> 0)
{
y = y +(x%8)* pow(10,n);



printf(%d\\\
,y);

x = x / 8;
n = n + 1;
}

printf(八进制等效为:%d,y);
返回0;

$ / code>

当我输入查找八进制等值的 1701 。它给出答案 3244

我想知道的是程序如何工作?

程序如何打印 3244 而不是 3245

但答案是 3245

我检查了 x%8 是否正常工作。

当我将 y 数据类型更改为浮点数时,
为什么如此?



请逐步解释转换如何影响输出。

如何截断小数位给我错误的答案?

解决方案

当您从浮点类型转换为整数类型时,机器将截断小数位,而不是整数。


I know that floating point cannot represent every number exactly so some error is bound to happen.

But recently I have encountered a problem and I am not getting the explanation right.

Please explain me step by step how the conversion affected the output.

How did truncating decimal places give me the wrong answer?

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

int main()
{
   int x;
   int y = 0;
   int n = 0;

   printf("Enter The Number You Want To Octal Equivalent Of : ");

   scanf("%d",&x);

   while(x>0)
   {
      y = y + (x%8)*pow(10,n);

      printf("%d\n" , y);

      x = x/8 ;
      n = n + 1;
   }

   printf("Octal Equivalent is : %d" , y);
   return 0;
}

When I enter find octal equivalent of 1701. It gives answer 3244.

What I want to know is how does the program working?
How is the program printing 3244 and not 3245.

But the answer is 3245.

I have checked that x%8 is correctly working .

When I change the y data type to float, it works . Why so?

Please explain me step by step how the conversion affected the output.
How did truncating decimal places give me the wrong answer?

解决方案

When you convert from a floating-point type to an integer type, the machine will truncate the decimal places, not round.

这篇关于浮动整数铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆