double to int conversion产生奇怪的结果 [英] double to int conversion yields strange results

查看:114
本文介绍了double to int conversion产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个程序,它以两种不同的方式将一个double转换为一个整数,给我两个不同的int值。基本的

表达式是1.0 /(1.0 * 365.0),应该是365,但是一个变量

变为364而另一个变为365.


有没有人对问题是什么有任何了解?


提前致谢。

Bj?rn


$ cat dc

#include< stdio.h>


int main(无效)

{

双dd,d = 1.0 / 365.0;

int n,nn;


n = 1.0 / d;

dd = 1.0 / d;

nn = dd;


printf(" n ==%d nn ==%d dd ==%f\ n",n,nn,dd);

返回0;

}


$ gcc -Wall -O0 -ansi -pedantic -W -Werror -od dc

$ ./d

n == 364 nn == 365 dd == 365.000000


$ gcc -v

从/usr/lib/gcc/i386-redhat-linux/3.4.2/specs阅读规格

配置为:../ configure --prefix = / usr --mandir = / usr / share / man

--infodir = / usr / share / info --enable-shared --enable- Ť hreads = posix

--disable-checking --with-system-zlib --enable -__ cxa_atexit

--disable-libunwind-exceptions --enable-java-awt = gtk

--host = i386-redhat-linux

线程模型:posix

gcc版本3.4.2 20041017(Red Hat 3.4。 2-6.fc3)

$

Below is a program which converts a double to an integer in two
different ways, giving me two different values for the int. The basic
expression is 1.0 / (1.0 * 365.0) which should be 365, but one variable
becomes 364 and the other one becomes 365.

Does anyone have any insight to what the problem is?

Thanks in advance.
Bj?rn

$ cat d.c
#include <stdio.h>

int main(void)
{
double dd, d = 1.0 / 365.0;
int n, nn;

n = 1.0 / d;
dd = 1.0 / d;
nn = dd;

printf("n==%d nn==%d dd==%f\n", n, nn, dd);
return 0;
}

$ gcc -Wall -O0 -ansi -pedantic -W -Werror -o d d.c
$ ./d
n==364 nn==365 dd==365.000000

$ gcc -v
Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.2/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --enable-shared --enable-threads=posix
--disable-checking --with-system-zlib --enable-__cxa_atexit
--disable-libunwind-exceptions --enable-java-awt=gtk
--host=i386-redhat-linux
Thread model: posix
gcc version 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)
$

推荐答案

cat dc

#include< stdio.h>


int main(无效)

{

double dd,d = 1.0 / 365.0;

int n,nn;


n = 1.0 / d;

dd = 1.0 / d;

nn = dd;


printf(" n ==%d nn ==%d dd ==%f\ n,n,nn,dd);

返回0;

}

cat d.c
#include <stdio.h>

int main(void)
{
double dd, d = 1.0 / 365.0;
int n, nn;

n = 1.0 / d;
dd = 1.0 / d;
nn = dd;

printf("n==%d nn==%d dd==%f\n", n, nn, dd);
return 0;
}


gcc -Wall -O0 -ansi -pedantic -W -Werror -od dc
gcc -Wall -O0 -ansi -pedantic -W -Werror -o d d.c


./ d

n == 364 nn == 365 dd == 365.000000

./d
n==364 nn==365 dd==365.000000


这篇关于double to int conversion产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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