0
#include <stdio.h>

typedef struct ElapsedTime_struct {
   int decadesVal;
   int yearsVal;
} ElapsedTime;

ElapsedTime ConvertToDecadesAndYears(int totalYears) {
   ElapsedTime tempVal;

   tempVal.decadesVal = totalYears/10;
   tempVal.yearsVal = (((double) totalYears/10) - tempVal.decadesVal) * 10;

   return tempVal;

}

int main(void) {
   ElapsedTime elapsedYears;
   int totalYears;

   scanf("%d", &totalYears);

   elapsedYears = ConvertToDecadesAndYears(totalYears);

   printf("%d decades and %d years\n", elapsedYears.decadesVal, elapsedYears.yearsVal);

   return 0;
}

my logic is that if you take number of total years( 26) and divide the integer value by 10, you will get the number of decades. int (26/10) = 2

my logic for the number of years is that if you take the double value of 26/10, you will get 2.6000

then subtracting 2.6 - 2 (number of decades), you will get the decimal value for the number of years(0.6)

i then multiplied by 10 to get a whole value (6) so together its 2 decades and 6 years.

however when i try running the code for some inputs (34 total years) i am getting 3 decades and 3 years for some reason whereas i should get 3 decades and 4 years.

i am confused as to why this is happening.

1 Answers1

2

Floating point math is inexact. Values such as 2.6 and 3.3 cannot be exactly represented in binary floating point. You instead end up with a value that is either slightly larger or slightly smaller.

The latter case is what you're seeing. 3.4 is stored as roughly 3.39999999999999991. Subtracting 3 from that and multiplying by 10 gives you 3.9999999999999991, then when you convert that to an int the fractional part is truncated giving you 3.

That being said, you don't need floating point operations here. You can instead use the modulus operator % to get the remainder when dividing by 10.

tempVal.yearsVal = totalYears%10;
dbush
  • 205,898
  • 23
  • 218
  • 273