Hey Folks,
I did a sample exercise in which to calculate the average hourly pay rate. Asked the user to enter the weekly pay (in euros as €12.51) and the weekly hours. These *had* to be read in as floating points. The output *had* to be in euro and cent separately.
Could you guys comment on whether the technique below is elegant enough or is cumbersome? This was really a test of playing with conversions and casts.
Just look at the *internal calculations* section and say whether it could be better done. I'm fairly happy with it - I'm not interesting trapping all cases at the moment - but want to see if this is the correct approach to get the cents and euros.
Again I really appreciate your kind comments.
Code:int main(void) { double weekly_pay = 0.0; double weekly_hours = 0.0; double average_pay_per_hour = 0.0; int euros = 0; int cents = 0; /* prompt user for weekly pay in euro and weekly hours worked */ printf("\nThis program will calculate your average hourly pay rate."); printf("\nPlease enter your weekly pay in euro: "); scanf("%lf", &weekly_pay); printf("Please enter your weekly hours worked: "); scanf("%lf", &weekly_hours); /* internal calculations */ average_pay_per_hour = weekly_pay / weekly_hours; euros = (int)average_pay_per_hour; /* keep the euro, knock the cent */ cents = (int)(average_pay_per_hour * 100) - euros*100; /* get cents */ /* display results */ printf("\nYour average hourly pay rate is %d euro and %d cents.\n",euros, cents); return 0; } /* Sample output: This program will calculate your average hourly pay rate. Please enter your weekly pay in euro: 105.1 Please enter your weekly hours worked: 10 Your average hourly pay rate is 10 euro and 50 cents



LinkBack URL
About LinkBacks




Yeah, thanks for that. It's cleaner and % is seen in many previous examples. I haven't done this in years but it's nice to get back into it. My thoughts at this stage are - "Oh my! I'm actually putting more thought into the var types and the manipulation of them rather the staightforward process of division." In Oracle, I rarely ever think about vars anymore - just NUMBER and VARCHAR2(X). But C is fun, and I can't wait to get back to the maze.c program from years back.