Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So i have this program that transform number of years into months , days and hours . It works good for transforming 1 year into all of those but when i try it with 0.5 years it transforms correctly the numbers of months and days but it puts 2190 hours instead of 4380 which is correct number and i cannot figure it out why

#include<stdio.h>
int main() 
{
	float years, months, days, hours;	
	scanf("%f", &years);
	months= 12*years;
    days= 365*years;
	hours= 24*years*days;
	printf("%f years si%f months\n",years,months);
    printf("%f years is%f days\n",years,days);
    printf("%f years is%f hours\n",years,hours);
	return 0;
}


What I have tried:

i just dont understand cause it should work good
Posted
Updated 30-Oct-22 9:49am

You are multiplying 24 by years and by days. But days have already been multiplied by the number of years so that total will be half what it should be.

As I suggested in my previous answer to you, try to read through your code more closely, and make the effort to solve simple errors for yourself. It will pay you in the long run as you will learn much more by trying to fix things for yourself rather than just posting the problem here.
 
Share this answer
 
Comments
Gafar Edin 30-Oct-22 12:26pm    
yea bro tnx , u are right
Richard MacCutchan 30-Oct-22 12:41pm    
If you expect to be taken seriously here, then please spell words in full, rather than using childish "txtspk".
Gafar Edin 30-Oct-22 12:46pm    
ok sorry . can you tell me how can i write the code correctly please?
Richard MacCutchan 30-Oct-22 16:10pm    
It's basic mathematics:
hours = 24 * days;
The calculation of the hours is obviously wrong:
C++
days= 365*years;
hours= 24*years*days;

If you insert days from the upper formula, you see that the year is squared, which is certainly not useful.
C++
hours= 24*years*years*365;
 
Share this answer
 
Comments
Gafar Edin 30-Oct-22 14:01pm    
hours=24*years*365 worked ..thank you
merano99 1-Nov-22 5:18am    
When calculating the days and derived quantities, it would probably be useful to consider leap years as well.
I would do it like this :
C++
#include<stdio.h>

int main()
{
	int years, months, days, hours;	
	scanf( "%d", &years );
	months = 12 * years;
    days = 365 * years;
	hours = 24 * days;
	printf( "%d years is %d months\n", years, months );
    printf( "%d years is %d days\n", years, days );
    printf( "%d years is %d hours\n", years, hours );
	return 0;
}
The key thing being these are all integer values. They do not need to be floating point.

It is important to note this code does not take into account leap years.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900