background

也没有啥新的东西,这一章都是格式化字符串

1

#include <stdio.h>

int main(void) {
char fname[50]; // 声明字符数组来存储名字
char lname[50]; // 声明字符数组来存储姓氏

printf("请输入名和姓:");
scanf("%s %s", fname, lname); // 使用 %s 格式接收字符串输入
printf("%s, %s", fname, lname);
return 0;
}

/*使用char[]数组来接收变量*/

2

#include<stdio.h>

int main(void){
char name[10];
int len;
printf("请输入姓名:");
scanf("%s",&name);
len=strlen(name);
printf("\"%s\"\n",name);
printf("\"%20s\"\n",name);
printf("\"%-20s\"\n",name);
printf("\"%*s\"",len+3,name);
}

/*%s还可以控制位置,*还可以占位*/

3

//4_3 读取一个浮点数,小数点计数法打印和指数计数法打印

#include <stdio.h>

int main(void){
float input;

printf("请输入一个浮点数:");
scanf("%f", &input);
printf("%.1f, %.1e\n", input, input);
printf("%f, %e", input, input);
return 0;
}
/*数据类型那点事 懒得看*/

4

#include <stdio.h>

int main(void){
float cm;
char name[50];

printf("请输入你的名字:");
scanf("%s", &name);
printf("\n请输入你的身高:");
scanf("%f", &cm);

printf("你好%s,你有%.2fM。",name,cm/100);
return 0;
}

/*格式化字符串问题*/

5

#include<stdio.h>
#define BIT_TO_BYTE 8 //每字节包含的位数

int main(void)
{
float m_speed;
float b_speed;
float file_size;
printf("Enter the download speed in megabits per second(Mbs): ");
scanf("%f",&b_speed);
m_speed = b_speed/BIT_TO_BYTE;
printf("Enter the size of a file in megabytes (MB):");
scanf("%f",&file_size);
printf("Download speed(MBs): %.2f\n",m_speed);
printf("File size(MB): %.2f\n",file_size);
printf("Download time(s): %.2f\n",file_size/m_speed);

return 0;
}

/*也是转来转去*/

6

#include<stdio.h>
#include<string.h>
int main(void)
{
char first_name[20];
char last_name[20];
printf("Enter your first name and last name: ");
scanf("%s",first_name);
scanf("%s",last_name);
printf("%s %s\n",first_name,last_name);
printf("%*d %*d\n",strlen(first_name),strlen(first_name),strlen(last_name),strlen(last_name));
printf("%s %s\n",first_name,last_name);
printf("%-*d %-*d\n",strlen(first_name),strlen(first_name),strlen(last_name),strlen(last_name));
return 0;
}

/*花拳绣腿*/

7

#include<stdio.h>
#include<float.h> //DBL_DIG, FLT_DIG

int main(void)
{
double num1 = 1.0/3.0;
float num2 = 1.0/3.0;
printf("double: %.4f %.12f %.16f\n",num1,num1,num1);
printf("float: %.4f %.12f %.16f\n",num2,num2,num2);
printf("DBL_DIG: %d\nFLT_DIG: %d",DBL_DIG,FLT_DIG);

return 0;
}

/*花拳绣腿*/

8

#include<stdio.h>

int main(void)
{
const float gallon_to_liter = 3.785; //每加仑相等的公升数
const float mile_to_kilometer = 1.609; //每英里相等的公里数
float traveled_miles;
float traveled_kilometers;
float gasoline_gallons;
float gasoline_liters;

printf("Enter the number of miles traveled: ");
scanf("%f",&traveled_miles);
printf("Enter the number of gallons of gasoline consumed: ");
scanf("%f",&gasoline_gallons);
printf("The miles-per-gallon Value: %.1f\n",traveled_miles/gasoline_gallons);

traveled_kilometers = traveled_miles*mile_to_kilometer; //英里转公里
gasoline_liters = gasoline_gallons*gallon_to_liter; //加仑转公升

printf("The liter-per-100-km value: %.1f\n",gasoline_liters/traveled_kilometers*100);

return 0;
}

/*使用const来定义常量
就是些单位的换算,编程本身的知识点前面已经练习过了*/