C 语言学习-03【输入与输出】
1、复合赋值语句
赋值语句:
#include <stdio.h> int main() { int i = 1, j = 5, m = 4, n = 3; j += i; m %= n; n += n -= n * n; printf("j = %d m = %d n = %d\n", j, m, n); char a = 'A', b, c; c = b = a + 1; printf("a = %c b = %c c = %c", a, b, c); return 0; }
- 运行结果:
2、字符输入函数 getchar()
getchar() 函数的用法:
#include <stdio.h> int main() { char ch; ch = getchar(); putchar(ch); putchar('\n'); putchar(getchar()); putchar(getchar()); putchar('\n'); putchar('c'); return 0; }
- 运行结果:
3、字符输出函数 putchar()
putchar() 函数的用法:
#include <stdio.h> int main() { char a = 'H', b = 'e', c = 'I', d = 'I', e = 'o'; putchar(a); putchar(b); putchar(c); putchar(d); putchar(e); putchar('\n'); putchar(a + 1); putchar('\n'); putchar('\101'); return 0; }
- 运行结果:
4、格式化输入函数 scanf()
scanf() 函数的用法:
#include <stdio.h> int main() { int i = 0; char ch = 0; float f = 0.0; scanf("i = %d, ch = %c, f = %f", &i, &ch, &f); printf("The values of the three variables are: \n"); printf("i = %d, ch = %c, f = %f\n", i, ch, f); printf("The address of ch in memory is: %o\n", &ch); printf("The address of ch in memory is: %d\n", &ch); printf("The address of ch in memory is: %x\n", &ch); return 0; }
- 运行结果:
5、d 格式控制字符
格式控制字符 d 的用法:
#include <stdio.h> int main(void) { int i = 123456; printf("%d\n", i); printf("%5d\n", i); printf("%8d\n", i); printf("%-8d\n", i); return 0; }
- 运行结果:
6、o and x 格式控制字符
格式控制字符 o 和 x 的用法:
#include <stdio.h> int main(void) { int a = 0, b = 1, c = -1; printf("%d, %o, %x\n", a, a, a); printf("%d, %o, %x\n", b, b, b); printf("%d, %o, %x\n", c, c, c); return 0; }
- 运行结果:
7、s 格式控制字符
m.ns 和 -m,ns 格式符:
#include <stdio.h> int main(void) { printf("%s\n", "Student"); printf("%7.3s\n", "Student"); printf("%-7.3s\n", "Student"); printf("%3.7s\n", "Student"); printf("%3.5s\n", "Student"); return 0; }
- 运行结果:
8、f 格式控制字符
%f、%m.nf 和 %-m.nf 格式符练习
#include <stdio.h> int main(void) { float f1 = 100.110000999; float f2 = 100.110000; float f3 = 123456.789; printf("%f\n", f1); printf("%f\n", f2); printf("%f\n", f3); printf("%10.1f\n", f3); printf("%5.1f\n", f3); printf("%12.3f****\n", f3); printf("%-12.3f****\n", f3); return 0; }
- 运行结果:
9、学生基本信息的输入和输出
数据的输入输出综合:
#include <stdio.h> int main() { int id, year, month, day; float chinese, math, score; char sex; printf("Please enter your student number: "); scanf("%d", &id); getchar(); printf("Please enter gender (can enter m or f): "); sex = getchar(); printf("Please enter the date (e.g. 2024/11/11): "); scanf("%d/%d/%d", &year, &month, &day); printf("Please enter your Chinese and math scores separated by Spaces: "); scanf("%f %f", &chinese, &math); score = chinese + math; printf("===========================================\n"); printf("Student information is shown below: \n"); printf("Student number: %d\n", id); printf("Sex: "); putchar(sex); printf("\ndate: %d/%d/%d\n", year, month, day); printf("chinese: %7.2f\n", chinese); printf("math: %-7.2f\n", math); printf("total score: %3.4f\n", score); return 0; }
- 运行结果: