检查double的条件是整数不起作用 [英] Condition to check double is an integer not working

查看:74
本文介绍了检查double的条件是整数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i 是整数或小数点后没有非零数字时,该程序应在小数点后输出零数字。它适用于所有情况,但不适用于最后一种情况。有人可以帮我解决这个问题吗?

This program was supposed to output zero digits after its decimal point when i is an integer or has no non-zero digit after decimal point. It works for all the cases just not for the last. Can anyone help me fix this?

代码:

#include <stdio.h>
#include<math.h>
int main()
{
    double i,j,k;
    for(i=0;i<=2;i=i+0.2)
    {
        k=3;
        j=i+1;
        while(k--)
        {
            if(fmod(i,1)==0) printf("I=%.0lf J=%.0lf\n",i,j);
            else printf("I=%.1lf J=%.1lf\n",i,j);
            j++;
        }
    }
}

这是 ideone示例执行

推荐答案

根据您的精度级别,可以使用如下所示的%g或%lg仅打印最短的可表示项。在此,我使用.5大小。

Depending on your precision level, you can use the %g or %lg like below to print just the shortest representable item. In this, I use the .5 size.

#include <stdio.h>
#include<math.h>
int main()
{
    double i,j,k;
    for(i=0;i<=2;i=i+0.2)
    {
        k=3;
        j=i+1;
        while(k--)
        {
            if(fmod(i,1)==0)
            {
                printf("I=%.5lg J=%.5lg\n",i,j);
            }
            else
            {
                printf("I=%.5lg J=%.5lg\n",i,j);
            }
            j++;
        }
    }
}

这篇关于检查double的条件是整数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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