Condition to check double is an integer not working

人走茶凉 提交于 2019-12-25 01:25:21

问题


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?

Code :

#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++;
        }
    }
}

Here's the ideone sample execution


回答1:


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++;
        }
    }
}


来源:https://stackoverflow.com/questions/54750758/condition-to-check-double-is-an-integer-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!