63 133
Assignments Done
99,1%
Successfully Done
In July 2018

Answer to Question #23917 in C# for fabricio

Question #23917
#include <stdio.h>
main()
{
int h1, m1, s1, h2, m2, s2, h3, m3, s3, oper, A, S;
printf("Please enter first clock:\n");
scanf("%d:%d:%d", &h1, &m1, &s1);
printf("Please enter second clock:\n");
scanf("%d:%d:%d", &h2, &m2, &s2);
printf("Enter A for addition or S for subtraction:\n");
scanf("%d", &oper);
{
if(oper=='S')
{
s3=(s1-s2);
m3=(m1-m2);
h3=(h1-h2);
if(s3<0)
{
s3=s3+60;
m3=m3;
h3=h3+24;
}
}
else
if(oper=='A');
{
s3=(s1+s2)%60;
m3=(m1+m2+((s1+s2)/60))%60;
h3=(h1+h2+((m1+m2)/60))%24;
}
}
printf("%2.2d:%2.2d:%2.2d\n", h3, m3, s3);
return 0;
}


the program only adds when i try to subtract instead of subtracting it adds them take a look n see if my if statement is wrong
Expert's answer
It is better to convert the times h1:m1:s1 and h2:m2:s2into seconds, then compute sum or difference and convert it to time.
Also it is better to make variable oper to be string(char *) and compare its first letter with 'A' and 'S'.

The program can look as follows:

#include <stdio.h>
int main()
{
int h1, m1, s1,h2, m2, s2, h3, m3, s3, t1, t2, t3;
char oper[30];
printf("Please enter first clock : ");
scanf("%d:%d:%d", &h1, &m1, &s1);
printf("Please enter second clock: ");
scanf("%d:%d:%d", &h2, &m2, &s2);
printf("Enter A for addition or S for subtraction: ");
scanf("%s", oper);
// convert bothtimes into seconds
t1 = s1 + 60*m1+ 3600*h1;
t2 = s2 + 60*m2+ 3600*h2;
// check thatthe operation is correct
if( (oper[0] !='S') && (oper[0] != 'A') )
{
printf("Wrong operation.
");
return 0;
}
// compute sumor difference
if (oper[0]=='A')
{
t3 = t1+t2;
}
else
{
t3 = t1-t2;
}
// make t3positive
while(t3<0)
{
t3+=24*60*60;
}
// convertobtained time t3 into the time inside 24 hours
// that is takethe remainder of division t3 by number of seconds in 24 hours
t3 = t3 %(24*60*60);

s3 = t3 % 60;// number of seconds in t3
t3 =(t3-s3)/60; // remove seconds from t3 and convert it to minutes

m3 = t3 % 60;// number of minutes in t3
t3 =(t3-m3)/60; // remove minutes from t3 and convert it to hours
h3 = t3%24; //number of hours
printf("%2.2d:%2.2d:%2.2d
", h3, m3, s3);
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions