问题
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