Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am creating a program to convert number of total years to decades and years. One of my outputs is being a little weird

#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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading