C - 为什么有些数字打印有小数位,即使我已经确定它们必须打印没有小数?

时间:2022-02-20 22:52:18

I'm trying to solve a question that says:

我正在尝试解决一个问题:

You must make a program in C that shows a sequence as in the example below:

您必须在C中创建一个显示序列的程序,如下例所示:

I=0 J=1
I=0 J=2
I=0 J=3
I=0.2 J=1.2
I=0.2 J=2.2
I=0.2 J=3.2
.....
I=2 J=?
I=2 J=?
I=2 J=?

I tried to solve this question using the "for" structure, but at the program output, the last three integers appear with decimal places, and the question requires that integers appear without decimal places:

我尝试使用“for”结构来解决这个问题,但是在程序输出中,最后三个整数显示小数位,并且问题要求整数出现时没有小数位:

I=0 J=1
I=0 J=2
I=0 J=3
I=0.2 J=1.2
I=0.2 J=2.2
I=0.2 J=3.2
.....
I=1 J=2
I=1 J=3
I=1 J=4
I=1.2 J=2.2
I=1.2 J=3.2
I=1.2 J=4.2
.....
I=2.0 J=3.0
I=2.0 J=4.0
I=2.0 J=5.0

Why does it happen? Here is my code:

为什么会这样?这是我的代码:

int main() {

  int II;
  float I, J, X, FI;
  X = 1;

  for(I = 0; I <= 2.2; I = I + 0.2){

      for(J = X; J <= X + 2; J = J + 1){

          II = (int) I;     //II = The Integer part of I
          FI = I - II;      //FI = The Fractionary part of I

          if(FI == 0)
              printf("I=%.0f J=%.0f\n", I, J);

              //If the fractionary part is 0, then
              //the number must be printed without
              //decimal places.              

          else
              printf("I=%.1f J=%.1f\n", I, J);

              //If the fractionary part is greater than 0,
              //then the number must be printed with just
              //one decimal place.

      }

      X += 0.2;
  }

  return 0;

}

If anyone can help me, I'll be very thankful.

如果有人能帮助我,我会非常感激。

1 个解决方案

#1


1  

Floating point numbers aren't always exact, you may need to do something like:

浮点数并不总是精确的,您可能需要执行以下操作:

if ((FI > -0.1) || (FI < 0.1))
   printf("I=%.0f J=%.0f\n", I, J);
else
   ...

OR

if (fabs(FI) < 0.1)
   printf("I=%.0f J=%.0f\n", I, J);
else
   ...

It is common practice not to compare floats/doubles for exactness, but within some small difference (epsilon) that depends on the particular application.

通常的做法是不比较浮点/双精度的准确性,而是在一些小的差异(ε)内,这取决于特定的应用。

#1


1  

Floating point numbers aren't always exact, you may need to do something like:

浮点数并不总是精确的,您可能需要执行以下操作:

if ((FI > -0.1) || (FI < 0.1))
   printf("I=%.0f J=%.0f\n", I, J);
else
   ...

OR

if (fabs(FI) < 0.1)
   printf("I=%.0f J=%.0f\n", I, J);
else
   ...

It is common practice not to compare floats/doubles for exactness, but within some small difference (epsilon) that depends on the particular application.

通常的做法是不比较浮点/双精度的准确性,而是在一些小的差异(ε)内,这取决于特定的应用。