cmath.hfmod

Fmod does not work as expected(c programming)


(the problem is caused by me and has been solved ,greetings from the newbie)I apologize to everyone, my function type was integer i just realized it, I opened it because I worked for hours, I have to delete it). I am using gcc 9.3.0 version and standard settings. In the code in the example, I am getting 7 while waiting to get output 7.14. What could be the reason for this?(im using gcc main.c -lm -o main when compiling,what I'm trying to do is print as an integer if the double number is equal to integer, otherwise print it as a double,sorry for the adjustments, this is the last and proper version)

#include <stdio.h>
#include <math.h>

int try(double a);

int main() {
  double b = 7.14;
  double x;
  double temp;

  x = try(b);

  if (fmod(x, 1) == 0.0) {  // print 7 in this function
    temp = x;
    printf("%d", (int)temp);
  } 
   else if (fmod(x, 1) != 0.0) {
    printf("%f", x);
  }

  return 0;
}

int try(double a) {
  if (fmod(a, 1) != 0.0) {
    printf("%lf", a);  // print 7.14 in this function
  } else if (fmod(a, 1) == 0.0) {
    printf("%d", (int)a);
  }

  return a + 0;
}

Solution

  • With gcc version 10.2.0 (GCC)

    Got the result 7.140000

    Some code-format and debug output.

    #include <math.h>
    #include <stdio.h>
    
    double func_try(double a) { return a + 0; }
    
    int main() {
      double b = 7.14;
      double x;
      x = func_try(b);
    
      printf("%lf\n", fmod(x, 1));
    
      if (fmod(x, 1) != 0.0) {
        printf("%lf", x);
      } else if (fmod(x, 1) == 0.0) {
        printf("%d", (int)x);
      }
    
      return 0;
    }
    
    $gcc main.c -lm -o main
    
    $./main
    0.140000
    7.140000