自学C第三天

本文解析了C Primer Plus 4.8中的两个问题:如何正确使用%.2f格式控制浮点输入,并通过示例展示了scanf和printf的使用技巧。后续章节涉及网络速度、文件大小计算,以及字符数组和浮点数精度控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}一次跑成功。

加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值