You are here:

C++/turbo c-comparing double to int


problem: when the c compares double to int equals to double it returns false;

#include <stdio.h>
int main
   int month;
   double day,date;
   printf("n enter a date (1-12:month).(1-7:sunday to saturday");
   scanf("n %lf ",&date);
   if (day!=(int)day) /* checks that the day is natural */
     return 1;
  return 0;

** when i enter date=12.7 for example the day equals 7.00 but the "day!=(int)(day)" returns true.  

I am not sure why you expect this to work.

Day is obvious equal to Day or itself so I am not sure why you are checking it.

If you are getting that (double) Day != (int) Day, it is because you are losing information when you convert from (double) to (int).  That is why the compiler complains about this when you try to do it without casting.  Even if you compare two number that are double that are supposed to be equal to 7.00 you may get that they are not equal because one could be 7.00 and the other could be 7.0000001 but you just did not print out enough significant digits.


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2017 All rights reserved.

[an error occurred while processing this directive]