第五章编程练习
5-1
#include <stdio.h> #define M_PER_H 60 int main() { int total_m, hour, minutes; do{ printf("Enter total minutes:"); scanf("%d", &total_m); hour = total_m / M_PER_H; minutes = total_m % M_PER_H; if (total_m <= 0){ hour = 0; minutes = 0; } printf("The time is:%02d:%02d.\n", hour, minutes); }while (total_m > 0); return 0; } /* Enter total minutes:123 The time is:02:03. Enter total minutes:288 The time is:04:48. Enter total minutes:666 The time is:11:06. Enter total minutes:-1 The time is:00:00. */
5-2
#include <stdio.h> int main() { int num; int cnt = 0; printf("Enter a number:"); scanf("%d", &num); while (cnt <= 10){ printf("%d\n", num+cnt ); cnt++; } return 0; }
5-3
#include <stdio.h> int main() { int days, day, week; int stop = 0; const int days_w = 7; do{ printf("Enter days:"); scanf("%d", &days); if (days <= 0){ stop = 1; printf("Bye!\n"); }else{ printf("%d days are %d weeks, %d days.\n", days, days/days_w, days%days_w); } }while (stop == 0); return 0; } /* Enter days:15 15 days are 2 weeks, 1 days. Enter days:0 Bye! */
5-4 与5-3基本一样,略过
5-5
#include <stdio.h> int main() { int money,days; int TotalMoney = 0; int cnt = 1; printf("Enter days to count:"); scanf("%d", &days); while(cnt++ <= days){ printf("How much money did you make today:"); scanf("%d", &money); TotalMoney = TotalMoney + money; } printf("You have made $ %d in %d days!\n", TotalMoney, days); return 0; } /* Enter days to count:5 How much money did you make today:1 How much money did you make today:2 How much money did you make today:3 How much money did you make today:4 How much money did you make today:5 You have made $ 15 in 5 days! */
5-6
#include <stdio.h> int main() { int sum, n = 0; //这种写法不对sum初始值不一定为0 int sum =0; int n; int i = 1; printf("Enter a num:"); scanf("%d", &n); while(i <= n){ sum = sum + i*i; i++; } printf("The summary is: %d", sum); return 0; } /* Enter a num:5 The summary is: 55 */
5-7
#include <stdio.h> float cube_f(float num); //函数原型声明结尾要有;号 int main() { float cube, n; printf("Enter a num:"); scanf("%f", &n); printf("The cube of %.3f is: %.3f", n, cube_f(n)); return 0; } float cube_f(float num){ return num * num * num; } /* Enter a num:3 The cube of 3.000 is: 27.000 */
5-8 5-9 略

浙公网安备 33010602011771号