#include <stdio.h>
int main(void)
{
int days, hours, mins;
float a, b, c, total, temp, tempA, tempB;
a = 3.56;
b = 12.50;
c = 9.23;
total = a+b+c;
days = total / 24;
temp = total/24 - days;
hours = temp * 24;
tempA = temp*24 - hours;
mins = tempA*60;
while (hours >= 24)
{
hours= hours-24;
days +=1;
}
while ( mins >= 60)
{
mins=mins-60;
hours +=1;
}
printf("days:%d\n", days);
printf("hours:%d\n", hours);
printf("mins:%d\n", mins);
return 0;
}
I wanted to convert decimal hours to real time and I can do it fine but I wanted to increase days hours if the hours is beyond 24 and if mins is beyond 60mins.
the while loop does subtract and it does print out the new value but the hours / days aren't getting compounded.
It was 1 day 1 hour 77mins
I wanted it to read 1 day 2 hours 17mins
but I'm getting 1 day 1 hour 17 mins.
Using the modulus operator will make your life much easier: it will give the remainder of a division.
int total;
/* a=; b=; c=; assignments */
total = a+b+c;
mins = total % 60;
total /= 60;
hours = total % 24;
days = total / 24;
Here is a simpler implementation of what you are trying to do:
void TimeFix(int &days, int &hours, int &mins)
{
hours += mins/60;
mins %= 60;
days += hours/24;
hours %= 24;
}
Running your program I'm getting:
days:1
hours:1
mins:17
and that's what I expect considering that total should be 25.29.
It works fine, your math is just a little off. (= (+ 3.56 12.50 9.23) 25.29), not 26.29.
Instead of a while loop you can use division:
days += hours / 24
hours %= 24
Also, do your minutes-to-hours stuff before your hours-to-days stuff.
Related
I've spent a good hour on this, but I can't create a formula that works for my c program. (I have a new programmer).
I have to convert UTC time to its respective time in a particular city. My code works perfectly except here. Here it gives me the wrong answer. I can't wrap my head around it (I created a formula but it makes no sense to me).
In my program, time is entered as 24 hour time. 9AM = 900, 12PM = 1200, 12am = 0 etc.
If we are asked to convert 2359 to Eucla time (UTC +845) my program outputs 804. The correct answer is 844.
I figured out how to calculate 844, but I make no sense of it.
2359 + 845 = 3204 (adding the timezone offset 845 to the UTC time)
3204 - 60 = 3144 (minus 60 for some reason [I followed my time overflow formula]
3144 - 2400 = 2400 (minus 2400 because time cannot be more than 2359)
How my program works
First plus UTC and offset time
calculatedTime = UTC + offset;
Then under that
if (calculatedTime < 2359) {
calculatedTime = calculatedTime - 2400;
}
I also have another function which checks for overflow time underneath
if (((calculatedTime > 59) && (calculatedTime < 99)) || ((calculatedTime > 159) && (calculatedTime < 199))) {
// All the way to 2359
calculatedTime = calculatedTime - 60 + 100;
}
You need to separate the time into hours and minutes. Then add the time zone offsets to the hours and minutes separately. Handle roll-over. Finally, recombine the hours and minutes into the final answer.
Like this:
int main(void)
{
// inputs
int time = 2359;
int zone = 845;
// separate hours and minutes
int timeHours = time / 100;
int timeMinutes = time % 100;
int zoneHours = zone / 100;
int zoneMinutes = zone % 100;
// add the hours and minutes
int hours = timeHours + zoneHours;
int minutes = timeMinutes + zoneMinutes;
// handle the rollover conditions
if (minutes > 60) {
minutes -= 60;
hours++;
}
if (hours > 24) {
hours -= 24;
}
// recombine the hours and minutes
int adjustedTime = hours * 100 + minutes;
printf("%d\n", adjustedTime);
}
Note that this code only works for timezones with positive offsets. You'll need to figure out how to make it work for negative time zones.
OP's code has various off-by-one errors.
// if (((calculatedTime > 59) && (calculatedTime < 99)) ||
// ((calculatedTime > 159) && (calculatedTime < 199))) {
if (((calculatedTime > 59) && (calculatedTime < 100)) ||
((calculatedTime > 159) && (calculatedTime < 200))) {
// if (hours > 24) {
// hours -= 24;
// }
if (hours >= 24) {
hours -= 24;
}
Also code has more clarity using values like 60, 100
if (((calculatedTime >= 60) && (calculatedTime < 100)) ||
((calculatedTime >= 60*2) && (calculatedTime < 100*2))) {
Yet OP's approach fails with negative numbers.
To cope with positive and negative time values, split the "hhmm" time into a hours and minutes. Look for conditions of "minute" overflow. I recommend 2 helper functions to split and combine results.
#include <stdio.h>
#include <stdlib.h>
void hhmm_split(int hhmm, int *hour, int *min) {
*hour = hhmm / 100;
*min = hhmm % 100;
}
/* `min` may be outside the primary range of (-60 ... 60) */
int hhmm_combine(int hour, int min) {
hour += min / 60;
min %= 60;
if (hour < 0 && min > 0) {
min -= 60;
hour++;
} else if (hour > 0 && min < 0) {
min += 60;
hour--;
}
hour %= 24;
return hour * 100 + min;
}
Test code
void hhmm_add(int t1, int t2) {
int t1_hh, t1_mm, t2_hh, t2_mm;
hhmm_split(t1, &t1_hh, &t1_mm);
hhmm_split(t2, &t2_hh, &t2_mm);
int sum = hhmm_combine(t1_hh + t2_hh, t1_mm + t2_mm);
printf("t1:% 05d + t2:% 05d = sum:% 05d\n", t1, t2, sum);
}
int main(void) {
hhmm_add(2359, 845);
hhmm_add(2359, -845);
hhmm_add(-2359, 845);
hhmm_add(-2359, -845);
}
Output:
t1: 2359 + t2: 0845 = sum: 0844
t1: 2359 + t2:-0845 = sum: 1514
t1:-2359 + t2: 0845 = sum:-1514
t1:-2359 + t2:-0845 = sum:-0844
Hi pretty new to coding in c, but would love your help in my following coding problem.
I want to add two times (that are in twenty four hour time notation already).
Currently they are both integers and the arithmatic addition function is great for whole hour (e.g. 800+1000), however because our / computer's numbers are base ten, it will not roll over to the next hour after 60min which leads to problems with addition.
I'm not sure if the modulus % can solve this? Ideally I would like to use simple c coding (that I understand), and not start importing timing keys into the program.
e.g.
#include <stdio.h>
int main (void)
{
int time1 = 1045; // 10:45am in 24hour time
printf("Time %d ",time1);
int time2 = 930; //9 hours & 30min
printf("+ time %d", time2);
int calc = time1 + time2;
printf(" should not equal ... %d\n", calc);
printf("\nInstead they should add to %d\n\n", 2015); //8:15pm in 24hr time
return 0;
}
Yes, you're correct that modulo division is involved. Remember, that is remainder division. This is more worthy as a comment since supplying a complete answer for problems like this is generally frowned upon, but it's too long for that; this should get you started:
#include <stdio.h>
int main(void)
{
// Assuming the given time has the format hhmm or hmm.
// This program would be much more useful if these were
// gathered as command line arguments
int time1 = 1045;
int time2 = 930;
// integer division by 100 gives you the hours based on the
// assumption that the 1's and 10's place will always be
// the minutes
int time1Hours = time1 / 100; // time1Hours == 10
int time2Hours = time2 / 100; // time2Hours == 9
// modulus division by 100 gives the remainder of integer division,
// which in this case gives us the minutes
int time1Min = time1 % 100; // time1Min == 45
int time2Min = time2 % 100; // time2Min == 30
// now, add them up
int totalHours = time1Hours + time2Hours; // totalHours = 19
int totalMin = time1Min + time2Min; // totalMin = 75
// The rest is omitted for you to finish
// If our total minutes exceed 60 (in this case they do), we
// need to adjust both the total hours and the total minutes
// Clearly, there is 1 hour and 15 min in 75 min. How can you
// pull 1 hour and 15 min from 75 min using integer and modulo
// (remainder) division, given there are 60 min in an hour?
// this problem could be taken further by adding days, weeks,
// years (leap years become more complicated), centuries, etc.
return 0;
}
I used this for a long time...
// convert both times hhmm to minutes an sum minutes
// be sure to do integer division
int time1m = ((time1 / 100) * 60)+(time1 % 100);
int time2m = ((time2 / 100) * 60)+(time2 % 100);
int sumMin = time1m + time2m;
// convert back to hhmm
int hhmm = ((sumMin / 60) * 100)+(sumMin % 60);
You can also include a day, as time is of 24 hour format.
#include <stdio.h>
int main()
{
int t1=2330;
int t2=2340;
int sum=((t1/100)*60)+(t1%100)+((t2/100)*60)+(t2%100);
int day=sum/(24*60);
sum = sum % (24*60);
int hours=sum/(60);
int mins=sum % 60;
printf("days = %d \t hours = %d \t mins=%d\n",day, hours, mins);
return 0;
}
I'm working through an example for Advanced Programming in the Unix Environment and the following questions was asked:
If the process time is stored as a 32bit signed integer, and the system counts 100 ticks per second, after how many days will the value overflow?
void proc_ovf()
{
int sec = 60;
int min = 60;
int hour = 24;
int tick = 100;
int epoch_time = (((INT_MAX / (sec * tick)) / min) / hour);
struct tm * timeinfo;
time_t epoch_time_as_proc_t = epoch_time;
timeinfo = localtime(&epoch_time_as_proc_t);
printf("3] overflow date of proc: %s", asctime(timeinfo));
}
Is the following solution a reasonable calculation for how many days before overflow?
(((INT_MAX / (sec * tick)) / min) / hour)
This calculation yielded 248 days.
248 days looks good.
But your code doesn't. Your variables have the wrong names. They should be:
int ticks_per_second = 100;
int seconds_per_minute = 60;
int minutes_per_hour = 60;
int hours_per_day = 24;
int ticks = INT_MAX;
int seconds = ticks / ticks_per_second;
int minutes = seconds / seconds_per_minute;
int hours = minutes / minutes_per_hour;
int days = hours / hours_per_day;
printf("overflow after %d days\n", days);
The above code takes care of mentioning the measurement units. Can you see how nicely the measurement units cancel out in each line of the second part of the code?
Essentially the program I've made adds time when the times are listed in the kind of military format (eg. 2300 is equal to 11pm) and then a duration is added (eg. 345, 3 hours 45 minutes.)
I've come across an issue in that when you add time to something that surpasses midnight it will continue to add past that. So for instance if you add 2 hours (200) to 11pm (2300) you will get a result of 2500 which is illogical for this purpose.
What I need my program to do is reach 2400 (midnight) and then reset to 0 but continue to add the remaining amount that needed to be added.
I've been trying to figure this out but I cannot figure out how I'm going to make it add what remains after you reset it to 0.
Since minutes are added modulo 60 and hours modulo 24, you need to handle them separately.
Something like
int add_time(int old_time, int addition)
{
/* Calculate minutes */
int total_minutes = (old_time % 100) + (addition % 100);
int new_minutes = total_minutes % 60;
/* Calculate hours, adding in the "carry hour" if it exists */
int additional_hours = addition / 100 + total_minutes / 60;
int new_hours = (old_time / 100 + additional_hours) % 24;
/* Put minutes and hours together */
return new_hours * 100 + new_minutes;
}
Break 24 hour/minute encode as a 4-digit int into hours and minutes. Avoid assuming values are in their primary range.
Add
Re-form time into the primary range.
Example
typedef struct {
int hour; // Normal range 0 - 23
int minute; // Normal range 0 - 59
} hhmm;
hhmm int_to_hhmm(int src) {
src %= 2400;
if (src < 0) src += 2400;
hhmm dest = { src / 100, src % 100 };
return dest;
}
int hhmm_to_int(hhmm src) {
src.hour += src.minute / 60;
src.minute %= 60;
if (src.minute < 0) {
src.minute += 60;
src.hour--;
}
src.hour %= 24;
if (src.hour < 0) {
src.hour += 24;
}
return src.hour * 100 + src.minute;
}
int add_mill_format_times(int t0, int t1) {
hhmm hhmm0 = int_to_hhmm(t0);
hhmm hhmm1 = int_to_hhmm(t1);
hhmm sum = { hhmm0.hour + hhmm1.hour, hhmm0.minute + hhmm1.minute };
return hhmm_to_int(sum);
}
you can do
addTime(int time1,int time2{
int first,last,addH,addM
last = func1(time1) + func2(time2);
last=last1+last2;
if(last > 60){
addH=last/60;
addM=last%60;
}
first=func2(time1)+func2(time2);
first+= addH;
last += addM;
first/=24;
return first*100 + addM;
}
func2(int time){
int i;
for(i=0;i<2;i++)
time/=10;
return time;
}
func1(int time){
int l=time%10;
time/=10;
int m=time%10;
return m*10 + l;
}
I'm new to coding and trying to figure out how to get code to round up to the next hour. The only method I've been able to think up (i.e. the only method I've been taught) is to just make else if statements for every hour. Clearly this isn't efficient at all and i know there's probably something much simpler. I was given a clue that there's a math equation involved?
Here's what i coded up so far:
#include <stdio.h>
int main()
{
//listens for value of "cost"
float cost;
printf("How much does this go-kart location charge per hour?\n");
scanf("%f", &cost);
//listens for value of "time"
float time;
printf("How many minutes can you spend there?\n");
scanf("%f", &time);
// i have to get it to round time to values of 60 (round up to next hour)
//really overcomplicated lack of knowledge workaround.txt
if (time < 60 && time > 0){
time = 1;
} else if(time > 61 && time < 70){
time = 2;
} else if(time > 71 && time < 80){
time = 3;
} else if(time > 81 && time < 90){
time = 4;
} else if(time > 91 && time < 100){
time = 5;
} else if(time > 101 && time < 160){
time = 6;
}
//etc etc
float total = cost * time;
printf("Your total will be $%f\n", total);
return 0;
}
For non regular intervals, one could do something like
int times[] = { 60; 70; 80; 90; 100; 160; INT_MAX }; // INT_MAX is to avoid segfault for bad input
int facts[] = { 1; 2; 3; 4; 5; 6; -1 }; // -1 is value for bad input
int it = 0;
while(times[it] < time) ++it;
int result = facts[it];
Note that you code doesnt have valid results for time = 60, 70, etc ... you should check the wanted behaviour
int hour = time/60;
if(60*hour < time)
++hour;
This is fairly basic math.
time / 60 would round down to to give you the hour.
Therefore (time / 60) + 1 rounds up.
If the maximum is 6 hours then simply check:
hour = time/60 + 1;
if (hour > 6) hour = 6;
Of course I'm assuming that time is an int. If it's a float then you can use floor or ceil to round up or down:
hour = floor(time/60 +1);
or
hour = ceil(time/60);
I think this is not bad
time = (time % 60) ? time / 60 + 1 : time / 60