浮动的变量用C [英] float variables in C

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

问题描述

可能这是一个简单的问题,但我不知道如何漂浮变量存储在内存中,为什么以这种方式行事,有人可以请有关以下行为的解释。

 #包括LT&;&stdio.h中GT;诠释的main()
{
    INT A = 9/5;
    的printf(%F \\ N,一);
    返回0;
}

输出:

  0.000000

我已经看过了如何浮动变量的一些信息都存储在内存中,它有东西约尾数,指数和符号。但我没有得到如何与这里。


解决方案

  int类型的= 9/5;

执行整数除法而忽略其余的,所以 A 设置为1,尝试打印,使用%F 给出不确定的行为,但你有机会 0.000000 出来。

不要

 双A = 9./5;

代替,或者用%d个打印,如果整数除法是所需的行为。 (浮动也将工作,但 A 将晋升为双击当传递给的printf ,所以没有理由不使用双击

May be this is a simple question but I am not sure about how float variables are stored in memory and why it is behaving in this way, can someone please explain about the following behavior.

#include<stdio.h>

int main ()
{
    int a = 9/5;
    printf("%f\n", a);
    return 0;
}

Output:

0.000000

I have looked at some information on how float variables are stored in memory, it has stuff about mantissa, exponent and sign. But I am not getting how to relate that here.

解决方案

int a = 9/5;

performs integer division and ignores the remainder, so a is set to 1. Attempting to print that using %f gives undefined behavior, but by chance you got 0.000000 out of it.

Do

double a = 9./5.;

instead, or print with %d if integer division was the desired behavior. (float would also work, but a will be promoted to double when passed to printf, so there's no reason not to use double.)

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

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