You are here:

C++/turbo c-comparing double to int

Advertisement


Question
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);
   month=int(date);
   day=(date-month)*10;
   if (day!=(int)day) /* checks that the day is natural */
    {
     printf("error");
     return 1;
     }
  return 0;
  }
     

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

Answer
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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

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.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.