C primer plus,4.8章节第5题卡住了
#include
int main(void)
{
float speed;
float size;
printf("Please enter the download speed of your internt: ");
scanf("%.2f", &speed);
printf("Please enter the file size you want to download: ");
scanf("%.2f", &size);
return 0;
}
其中scanf中,%.2f应为%f,首先在输入中精确到小数点后两位没有意义,其次会出现只能输入speed无法输入size,但改为%f后全都可以正常输入,暂时还不清楚原因。
这题的正确答案是:
#include
#define BIT 8
int main(void)
{
float speed, size, time;
printf("Please enter net speed(Mbit/s):");
scanf("%f", &speed);
printf("Please enter file size(MB):");
scanf("%f", &size);
time = size * BIT / speed;
printf("At %.2f megabits per secnod, ", speed);
printf("a file of %.2f megabytes ", size);
printf("downloads in %.2f seconds.\n", time);
return 0;
}
4.8第6题
#include
#include
int main(void)
{
char first_name[20];
char last_name[20];
int x, y;
printf("Please enter your first name: ");
scanf("%s", first_name);
printf("Please enter your last name: ");
scanf("%s", last_name);
x = strlen(first_name);
y = strlen(last_name);
printf("%s %s\n", first_name, last_name);
printf("%*d %*d\n", x, x, y, y); #注:*号可以定义要打印的字段宽度,需要赋值,宽度默认是从左向右打印的,如果*值是7,要打印的字是C,就会有6个空格加一个C
printf("%s %s\n", first_name, last_name);
printf("%-*d %-*d", x, x, y, y); #注:-*星号前面有一个减号,意思是会从左往右打印。
return 0;
4.8 第7题:
#include
#include
int main(void)
{
double a;
float b;
a = 1.0/ 3.0; #注:需要用1.0/3.0小数必须保留,因为定义的是浮点数,如果用1/3打印出来会是0.0000
b = 1.0 / 3.0;
printf("%.16f\n", a); #注:double和float在小数前6位没有区别,但在12和16位后double的值会高于float
printf("%.16f\n", b);
printf("FLT_DIG = %d, DBL_DIG = %d\N", FLT_DIG, DBL_DIG);
return 0;
4.8 第8题:
#include
int main(void)
{
const float g_l = 3.785;
const float m_km = 1.609;
float t_m, gas_g, t_km, gas_l;
printf("Please enter how many miles you travled: ");
scanf("%f", &t_m);
printf("Please enter how many gallon of gas you used: ");
scanf("%f", &gas_g);
t_km = t_m * m_km;
gas_l = gas_g * g_l;
printf("You have traveld for %.1f km and used %.1f L gas\n",
t_km, gas_l);
printf("And the for each km your car cost %.1f L gas",
t_km / gas_l);
return 0;
}一次跑成功。
加油!