-2

(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;
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257

2 Answers2

0

fmod(7.14, 1) = 0.14, thus it hit the first if and print 7.14.

Compute remainder of division

Returns the floating-point remainder of numer/denom (rounded towards zero):

fmod = numer - tquot * denom

Where tquot is the truncated (i.e., rounded towards zero) result of: numer/denom.

http://www.cplusplus.com/reference/cmath/fmod/

delta
  • 3,778
  • 15
  • 22
0

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
Zongru Zhan
  • 546
  • 2
  • 8