C Primer Plus_第四章_字符串和格式化输入输出_编程练习

时间:2023-03-08 15:35:10

Practice

1.输入名字和姓氏,以“名字,姓氏”的格式输出打印。

#include
int main(void)
{
char name[20];
char family[20];
printf("My Handsome Master, please enter your name:
\n");
scanf("%s %s", &name, &family);
//名字和姓氏一起读的话,需要先输入名字再输入姓氏,中间要有空白字符(空格、制表、换行)
printf("\"%s,%s\"!\n", name, family);//注意双引号的转义字符
return 0;
}

2.输入名字,以一定格式(略)输出。
#include
#include

int main(void)
{
char name[20];
int length = 0;

printf("please enter your name: \n");
scanf("%s", name);
printf("1: \"%s\"\n", name);
printf("2: \" s\"\n", name);
printf("3: \"%-20s\"\n", name);
length = strlen(name) + 3;
printf("4: \"%*s\"\n", length, name);//注意*代表输出宽度length  ! !
!

return 0;
}

3. 题略
#include
int main(void)
{
float f;
printf("please enter a float number: \n");
scanf("%f", &f);
printf("a. The input is %0.1f or %0.1e\n", f, f);
printf("b. The input is +%5.3f or %4.3e\n", f, f);

return 0;
}

4.题略
#include
int main(void)
{
char name[30];
float height;

printf("My owner, please enter your name and height (eg: tom
180): \n");
scanf("%s %f", &name, &height);
printf("Dear %s, you are %.3f cm tall\n", name, height);

return 0;
}

5.题略
#include
#include

int main (void)
{
char name[10];
char fame[10];
int num1 = 0;
int num2 = 0;

printf("Please enter your name:\n");
scanf("%s",name);
num1 = strlen(name);
printf("Please enter your famliy name:\n");
scanf("%s",fame);
num2 = strlen(fame);
printf("%s %s\n%*d
%*d\n",name,fame,num1,num1,num2,num2);
printf("%s %s\n%-*d
%-*d\n",name,fame,num1,num1,num2,num2);
//注意*的使用

return 0;
}
结果如下图
6.题略

#include
#include

int main(void)
{
float num_f = 0;
double num_d = 0;
num_f = 1 / 3;
num_d = 1 / 3;
 
     
%num_f = 1.0 / 3.0;
%num_d = 1.0
/ 3.0;

printf("%.4f\n%.12f\n%.16f\n\n", num_f, num_f, num_f);
printf("%.4lf\n%.12lf\n%.16lf\n\n", num_d, num_d,
num_d);
printf("%d\n%d\n",FLT_DIG,DBL_DIG);
return 0;
}
结果显示
上网一查得到说法如下:
语法没有错,可以这样写,不过f的值是0.0

因为数字在C/C++中默认的类型是int,两个int的四则运算结果仍然是int

所以1/3=0.33333……,强制转化成int后结果为0,再将int的0赋值给float类型的f,强制转化后就是0.0,所以不是你想要的结果0.3333……,

如果想得到0.3333……,应该这样写:

float f = (float) 1 / 3 或 f = 1 / (float) 3

或者

float f = 1.0 / 3 或 f = 1 / 3.0 或 f = 1.0 / 3.0

对于double型数据,小数点后超过15位后的数据不能保证精度。

7.题略
最后一题了,好像不是很难,懒得做了,饿死了要吃晚饭了,直接复制一份网上的答案到vs2010环境下,尼玛,居然检测出来是复制到网页上的答案,还报错了。尼玛,真是吊啊
解决办法,先复制到TXT文档里,结果还是不行,再复制到word里,这才行了

#include
#define GALLON 3.785  //1 gallon = 2.785
litre
#define MILE 1.609   //1 mile = 1.609
kilometer

int main(void)
{
float mile,gallon;
printf("Please input miles and gallons:");
scanf("%f %f",&mile,&gallon);
printf("Miles per
gallon:%.1f\n",mile/gallon); 
printf("Litres per 100
kilometre:%.1f\n",gallon*GALLON/(100*mile*MILE));
%getchar();
%getchar();
return(0);
}
好像最后的结果有点问题,懒得改了,饿了,要吃饭了,不然胃疼又不值得了(这题不难关键)