您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-18 09:55 609 查看
学习总结

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

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

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

#include <stdio.h>
int main(void){
char name[40];
printf("what's your name?\n");
scanf("%s",name);
printf("hello %s!\n",name);
return 0;
}


运行结果:

what's your name?

tom green

hello tom!

#include <stdio.h>
int main(void){
char name[40];
printf("what's your name?\n");
gets(name);
printf("hello %s!\n",name);
return 0;
}


运行结果:

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):

#include <stdio.h>
#define J2S 3.785
#define Y2G 1.609
int main(){
double mile,gallon;
printf("enter your mile:");
scanf("%lf",&mile);
printf("enter your gallon:");
scanf("%lf",&gallon);
printf("your oil wear is %.1f\n",mile/gallon);
printf("your CHN oil wear is %.1f\n",mile*Y2G/(gallon*J2S));
}


运行结果:

enter your mile:100

enter your gallon:50

your oil wear is 2.0

your CHN oil wear is 0.9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: