【C语言学习】《C Primer Plus》第4章 字符串和格式化输入/输出

学习总结

 

1、String str=”hello world!”;(Java),char[20]=” hello world!”;(C)。其实Java字符串的实现,也是字符数组。

 

2、字符串的尾部都会以空字符()结束,所以” hello world! “这个字符数组的长度是13。<string.h>函数库有个strlen()函数可以计算机字符串的字符数组长度(不包括空字符)。

 

3、scanf(“%s”,name)和gets的差别:

1 #include <stdio.h>
2 int main(void){
3         char name[40];
4         printf("what's your name?
");
5         scanf("%s",name);
6         printf("hello %s!
",name);
7         return 0;
8 }

运行结果:

what's your name?

tom green

hello tom!

1 #include <stdio.h>
2 int main(void){
3         char name[40];
4         printf("what's your name?
");
5         gets(name);
6         printf("hello %s!
",name);
7         return 0;
8 }

运行结果:

what's your name?

tom green

hello tom green!

4、#define可用于常量定义,格式:#define NAME value,编译器在编译前会把所有NAME替换为value后在编译,相当于单纯“面值”的替换。如果value是组合元素的话,最好括号,如#define SUM (x+y),以防这种“文字游戏”引起的错乱。

 

5、C常量的另一种表示可以使用const关键字,如const int months=12。那么months就是一个常量了。总之const修饰的对象就是常量,不可以修改。

 

6、编程练习(题7):

 1 #include <stdio.h>
 2 #define J2S 3.785
 3 #define Y2G 1.609
 4 int main(){
 5         double mile,gallon;
 6         printf("enter your mile:");
 7         scanf("%lf",&mile);
 8         printf("enter your gallon:");
 9         scanf("%lf",&gallon);
10         printf("your oil wear is %.1f
",mile/gallon);
11         printf("your CHN oil wear is %.1f
",mile*Y2G/(gallon*J2S));
12 }

运行结果:

enter your mile:100

enter your gallon:50

your oil wear is 2.0

your CHN oil wear is 0.9

原文地址:https://www.cnblogs.com/wcd144140/p/4511194.html