C primer plus
第5章第一题
#include
#define h_m 60;
int main(void)
{
int mins, hours, l_mins;
printf("Please enter the number of mintues(enter 0 to quit): ");
scanf("%d", &mins); #注:非数组&号一定不能漏掉,不然会报错,没有初始化mins
while (mins > 0) {
hours = mins / h_m;
l_mins = mins % h_m;
printf("you have spent %d hours and %d mintues\n",
hours, l_mins);
printf("Please enter the number of mintues (enter 0 to quit): ");
scanf("%d", &mins);
}
return 0;
}
第二题:
#include
int main(void)
{
int a, b;
b = 1;
printf("Please enter a number: ");
scanf("%d", &a);
while (b++
{
a = ++a;
printf("%d\n", a -1);
}
return 0;
}
第三题:
#include
#define one_week 7
int main(void)
{
int days, week, days_lt;
printf("Please enter how many days(enter 0 to quit): ");
scanf("%d", &days);
while (days > 0)
{
week = days / one_week;
days_lt = days % one_week;
printf("%d days are %d weeks, %d days\n", days, week, days_lt);
printf("Please enter how many days(enter 0 to quit): ");
scanf("%d", &days);
}
return 0;
}
第4题
这题因为小数和整数问题卡了很久,%求余数只能用整数而不能用小数,所以inch公式需要推导出来的。
#include
#define cm_inch 2.54 #注:看了标准答案,2.54和30.48后面都跟了f 表示单精度。
#define inch_feet 12
#define cm_feet 30.48
int main(void)
{
float h_cm, h_inch;
int h_feet;
printf("Enter a height in centimeters: ");
scanf("%f", &h_cm);
while (h_cm > 0)
{
h_feet = h_cm / cm_feet;
h_inch = h_cm / cm_inch - inch_feet * h_feet;
printf("%.1f cm = %d feet, %.2f inches\n", h_cm, h_feet, h_inch);
printf("Enter a height in centimeters: "); #注:千万别把printf里的内容写到scanf里,C不是python
scanf("%f", &h_cm);
}
printf("bye!");
return 0;
}
第5题:做了少许改动。
#include
int main(void)
{
int earn, days, working, sum;
working = 0;
earn = 0;
sum = 0;
printf("Please enter your working days: ");
scanf("%d", &days);
while (working < days)
{
earn = ++earn;
sum = sum + earn;
working = working++;
printf("You will earn $%d, total earn $%d for working %d days\n",
earn, sum, working);
}
return 0;
}
今天因为有事学习的时间偏少了,之后几天补回来!
加油!