C语言学习(四)C控制语句:循环、分支和跳转

参考书:《C Primer Plus》第六版


  1. for循环。程序清单1

  2. 出口条件循环:do while。程序清单2

  3. 关系运算符的优先级比算术运算符低,关系运算符的优先级比赋值运算符高。

  4. 注意:使用数组时,c编译器不会检查数组的下标是否正确,这里可能会导致潜在的异常。

  5. if else语句。程序清单3

  6. ctype.c头文件中包含一些专门处理字符的函数的原型,这些函数接受一个字符作为参数,返回一个数值,如isalpha()函数如果输入参数是一个字母则返回非零值。

  7. 函数名如果是下列参数时返回值为真
    isalnum()字母或数字
    isalpha()字母
    isblank()标准的空白字符(空格、水平制表符或换行符)或任何其它本地化为空白的字符
    iscntrl()控制字符,如Ctrl+B
    isdigit()数字
    isgraph()除空格之外的任意可打印字符
    islower()小写字符
    isprint()可打印字符
    ispunct()标点符号(空格、换行符、换页符、回车符、垂直制表符、水平制表符或其它本地化定义的字符)
    isupper()大写字符
    isxdigit()十六进制数字符
  8. 另外ctype.h头文件中还有字符映射函数:tolower()toupper()

  9. 逻辑运算符:&&||!,另外,C99标准新增了可代替逻辑运算符的拼写,他们被定义在iso646.h头文件中,如果程序中包含该头文件,则可用and代替&&or代替||not代替!

  10. 一个统计单词的程序如程序清单4

  11. C语言中唯一的三元运算符:条件运算符,如x=(y<0)?-y:y;

  12. 循环辅助:continue语句,执行该语句时,跳过本次迭代的剩余部分并开始下一轮迭代。break语句,终止包含它的循环并继续执行下一阶段。

  13. 多重选择switchbreak程序清单5

程序清单1

#include<stdio.h>


int main(void) {
	int num;
	printf("    n  n cubed\n");
	for (num = 1; num <= 6; ++num) {
		printf("%5d %5d\n", num, num * num * num);
	}

	return 0;
}

输出

    n  n cubed
    1     1
    2     8
    3    27
    4    64
    5   125
    6   216

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 28332)已退出,代码为 0。
按任意键关闭此窗口. . .

程序清单2

#include<stdio.h>


int main(void) {
	const int secret_code = 13;
	int code_entered;
	do {
		printf("To enter the triskaidekaphobia therapy club,\n");
		printf("please enter the secret code number:");
		scanf_s("%d", &code_entered);
	} while (code_entered != secret_code);
	printf("Congratulations! You are cured!");
	return 0;
}

输出

To enter the triskaidekaphobia therapy club,
please enter the secret code number:12
To enter the triskaidekaphobia therapy club,
please enter the secret code number:11
To enter the triskaidekaphobia therapy club,
please enter the secret code number:13
Congratulations! You are cured!
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 27016)已退出,代码为 0。
按任意键关闭此窗口. . .

程序清单3

#include<stdio.h>
#define SPACE ' '

int main(void) {
	char ch;
	ch = getchar();
	while (ch!='\n')
	{
		if (ch == SPACE)
			putchar(ch);
		else
			putchar(ch + 1);
		ch = getchar();
	}
	putchar(ch);

	return 0;
}

输出

asdfasd
btegbte

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 32428)已退出,代码为 0。
按任意键关闭此窗口. . .

程序清单4

#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
#define STOP '|'

int main(void) {
	char c;
	char prev;
	long n_chars = 0L;//字符数
	int n_lines = 0;//行数
	int n_words = 0;//单词数
	int p_lines = 0;//不完整的行数
	bool inword = false;//如果c在单词中为true
	printf("Enter text to be analyzed () to terminate):\n");
	prev = '\n';
	while ((c = getchar()) != STOP) {
		n_chars++;
		if (c == '\n')
			n_lines++;
		if (!isspace(c) && !inword)
		{
			inword = true;
			n_words++;
		}
		if (isspace(c) && inword)
			inword = false;
		prev = c;
	}
	if (prev != '\n')
		p_lines = 1;
	printf("characters=%1d, words=%d, lines=%d, ", n_chars, n_words, n_lines);
	printf("partial lines =%d\n", p_lines);

	return 0;
}

输出

Enter text to be analyzed () to terminate):
reason is a
powerful servant but
an inadequate master.
|
characters=55, words=9, lines=3, partial lines =0

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 28616)已退出,代码为 0。
按任意键关闭此窗口. . .

程序清单5

#include<stdio.h>
#include<ctype.h>

int main(void) {
	char ch;
	printf("Give me a letter of the alphabet, and I will give ");
	printf("an animal name\nbeginning with that letter.\n");
	printf("please type in a letter; type # to end my act.\n");
	while ((ch = getchar()) != '#') {
		if ('\n' == ch)
			continue;
		if (islower(ch))
			switch (ch)
			{
			case 'a':
				printf("argali, a wild sheep if Asia\n");
				break;
			case 'b':
				printf("babirusa, a wild pig of Malay\n");
				break;
			case 'c':
				printf("coati,racoonlike mammal\n");
				break;
			case 'd':
				printf("desman, aquatic, molelike critter\n");
				break;
			case 'e':
				printf("echidna, the spiny anteater\n");
				break;
			case 'f':
				printf("fisher, brownish marten\n");
				break;
			default:
				printf("That's a stumper!\n");
			}
		else
			printf("I recongnize only lowercase letters.\n");
		while (getchar() != '\n')
			continue;
		printf("please type another letter or a #.\n");
	}
	printf("Bye!\n");
	return 0;
}

输出

Give me a letter of the alphabet, and I will give an animal name
beginning with that letter.
please type in a letter; type # to end my act.
a
argali, a wild sheep if Asia
please type another letter or a #.
r
That's a stumper!
please type another letter or a #.
dab
desman, aquatic, molelike critter
please type another letter or a #.
r
That's a stumper!
please type another letter or a #.
q
That's a stumper!
please type another letter or a #.
#
Bye!

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 25436)已退出,代码为 0。
按任意键关闭此窗口. . .


循环–示例(均来自课后习题)

示例1:编写一个程序,创建包含26个元素的数组,并在其中存储26个小写字母,然后打印数组的所有内容。

#include<stdio.h>

int main(void) {
	char chars[27] ;
	char c = 'a';
	for (int i=0;i<26;i++)
		chars[i] = c++;
	chars[26] = '\0';
    //注意字符数组也就是字符串的最后一个字符必须要是\0,否则用printf输出时字符串末尾会出现乱码
	//scanf_s("%s", chars,26);
	printf("%s", chars);
	return 0;
}

输出:

abcdefghijklmnopqrstuvwxyz
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 15260)已退出,代码为 0。
按任意键关闭此窗口. . .

示例2:用嵌套循环打印字符

#include<stdio.h>

int main(void) {
	for (int i = 0; i < 5; ++i) {
		for (int j = 0; j <= i; ++j)
			printf("$");
		printf("\n");
	}
		
	return 0;
}

输出

$
$$
$$$
$$$$
$$$$$

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 17372)已退出,代码为 0。
按任意键关闭此窗口. . .

示例3:用嵌套循环打印字符

#include<stdio.h>

int main(void) {
	for (int i = 0; i < 6; ++i) {
		for (int j = 0; j <= i; ++j)
			printf("%c",'F'-j);
		printf("\n");
	}
		
	return 0;
}

输出

F
FE
FED
FEDC
FEDCB
FEDCBA

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 24228)已退出,代码为 0。
按任意键关闭此窗口. . .

示例4:用嵌套循环打印字母

#include<stdio.h>

int main(void) {
	char a = 'A';
	for (int i = 0; i < 6; ++i) {
		for (int j = 0; j <= i; ++j)
			printf("%c",a++);
		printf("\n");
	}
		
	return 0;
}

输出

A
BC
DEF
GHIJ
KLMNO
PQRSTU

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 19304)已退出,代码为 0。
按任意键关闭此窗口. . .

示例5:提示用户输入一个大写字母,用嵌套循环以金字塔型格式打印字母

#include<stdio.h>
#include<ctype.h>
int main(void) {
	char a ;
	printf("请输入一个大写字母:");
	while (!isupper(a = getchar()));
	for (int i = 0; i < 5; ++i) {
		for (int j = 0; j <= 4-i; ++j)
			printf(" ");
		for (int j = 0; j <= i; ++j)
			printf("%c", a - 4 + j);
		for (int j = 1; j <= i; ++j)
			printf("%c", a - 5 +j);
		printf("\n");
	}
		
	return 0;
}

输出

请输入一个大写字母:E
     A
    ABA
   ABCAB
  ABCDABC
 ABCDEABCD

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 20608)已退出,代码为 0。
按任意键关闭此窗口. . .

示例6:打印一个表格,每一行打印一个整数、该整数的平方、该整数的立方。要求用户输入表格的上下限。

#include<stdio.h>
#include<ctype.h>
int main(void) {
	int max,min;
	printf("Please enter two values for max and min: ");
	scanf_s("%d %d", &max, &min);
	for (int i = min; i <= max; ++i) {
		printf(" %d    %d    %d  \n", i, i * i, i * i * i);
	}
	return 0;
}

输出

Please enter two values for max and min: 20 11
 11    121    1331
 12    144    1728
 13    169    2197
 14    196    2744
 15    225    3375
 16    256    4096
 17    289    4913
 18    324    5832
 19    361    6859
 20    400    8000

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 36808)已退出,代码为 0。
按任意键关闭此窗口. . .

示例7:读入一个单词然后倒序打印

#include<stdio.h>
#include<string.h>
int main(void) {
	char word[40];
	scanf_s("%s", word, 40);
	for (int i = 0; i < strlen(word); ++i)
		printf("%c", word[strlen(word) - i - 1]);
	return 0;
}

输出

TheWorld
dlroWehT
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 944)已退出,代码为 0。
按任意键关闭此窗口. . .

示例8:输入两个浮点数,打印两数之差除以两数乘积的结果,循环计算直到用户输入非数字。

#include<stdio.h>
//#include<string.h>
#include<ctype.h>
int main(void) {
	float v1, v2;
	printf("Enter the first value: ");
	scanf_s("%f", &v1);
	printf("Enter the second value: ");
	while (scanf_s("%f", &v2)) {
		printf("(%f-%f)/(%f*%f))= %f\n",v2,v1,v1,v2, (v2 - v1) / (v1 * v2));
		v1 = v2;
		printf("Enter the next value: ");
	}
	return 0;
}

输出

Enter the first value: 2.
Enter the second value: 3.
(3.000000-2.000000)/(2.000000*3.000000))= 0.166667
Enter the next value: 6.
(6.000000-3.000000)/(3.000000*6.000000))= 0.166667
Enter the next value: 4.
(4.000000-6.000000)/(6.000000*4.000000))= -0.083333
Enter the next value: 7.
(7.000000-4.000000)/(4.000000*7.000000))= 0.107143
Enter the next value: z

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 30780)已退出,代码为 0。
按任意键关闭此窗口. . .

示例9:修改示例8,使用函数计算。

#include<stdio.h>
//#include<string.h>
#include<ctype.h>
float cal(float v1, float v2) {
	return (v2 - v1) / (v1 * v2);
}
int main(void) {
	float v1, v2;
	printf("Enter the first value: ");
	scanf_s("%f", &v1);
	printf("Enter the second value: ");
	while (scanf_s("%f", &v2)) {
		printf("(%f-%f)/(%f*%f))= %f\n",v2,v1,v1,v2, cal(v1,v2));
		v1 = v2;
		printf("Enter the next value: ");
	}
	return 0;
}

输出

Enter the first value: 5.
Enter the second value: 7.
(7.000000-5.000000)/(5.000000*7.000000))= 0.057143
Enter the next value: 3.
(3.000000-7.000000)/(7.000000*3.000000))= -0.190476
Enter the next value: 55.
(55.000000-3.000000)/(3.000000*55.000000))= 0.315152
Enter the next value: a

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 36768)已退出,代码为 0。
按任意键关闭此窗口. . .

示例10:输入一个上限整数和一个下限整数,计算从上限整数到下限整数范围内的所有整数的平方和并打印出来,重复这一步骤直到上限整数小于等于下限整数。

#include<stdio.h>
//#include<string.h>
#include<ctype.h>
int main(void) {
	int max, min;
	printf("Enter lower and upper integer limits: ");
	scanf_s("%d %d", &min, &max);
	while (max > min) {
		int sum = 0;
		for (int i = min; i <= max; ++i)
			sum += i * i;
		printf("The sums of the squares from %d to %d is %d\n",min,max,sum);
		printf("Enter next set  of limits: ");
		scanf_s("%d %d", &min, &max);
	}
	printf("Done\n");
return 0;
}

输出

Enter lower and upper integer limits: 5 9
The sums of the squares from 5 to 9 is 255
Enter next set  of limits: 3 25
The sums of the squares from 3 to 25 is 5520
Enter next set  of limits: 5 5
Done

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 14192)已退出,代码为 0。
按任意键关闭此窗口. . .

示例11:在数组中读入8个整数,然后倒序打印这8个整数。

#include<stdio.h>

int main(void) {
	int arr[8];
	for (int i = 0; i < 8; ++i)
		scanf_s("%d", &arr[i]);
	for (int i = 7; i >= 0; --i)
		printf(" %d ", arr[i]);

return 0;
}

输出

12
234
123
123
234
222
333
22
 22  333  222  234  123  123  234  12
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 32232)已退出,代码为 0。
按任意键关闭此窗口. . .

示例12:计算两个无限序列

#include<stdio.h>

int main(void) {
	int times;
	printf("Please enter a value: ");
	scanf_s("%d", &times);
	while (times > 0) {
		double sum1 = 0.,sum2=0.;
		for (int i = 0; i < times; ++i) {
			sum1 += 1.0 / (double)(i + 1);
			double sign = (i % 2) ? 1. : -1.;
			sum2 += sign * 1.0 / (double)(i + 1);
		}
		printf("1.0 +1.0/2.0+ ...=%lf\n", sum1);
		printf("1.0-1.0/2.0+...=%lf\n", sum2);
		printf("Enter another value: ");
		scanf_s("%d", &times);
	}
	printf("End.");

return 0;
}

输出

Please enter a value: 10
1.0 +1.0/2.0+ ...=2.928968
1.0-1.0/2.0+...=-0.645635
Enter another value: 100
1.0 +1.0/2.0+ ...=5.187378
1.0-1.0/2.0+...=-0.688172
Enter another value: 1000
1.0 +1.0/2.0+ ...=7.485471
1.0-1.0/2.0+...=-0.692647
Enter another value: 10000
1.0 +1.0/2.0+ ...=9.787606
1.0-1.0/2.0+...=-0.693097
Enter another value: 100000
1.0 +1.0/2.0+ ...=12.090146
1.0-1.0/2.0+...=-0.693142
Enter another value: 0
End.
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 27476)已退出,代码为 0。
按任意键关闭此窗口. . .

示例13:创建一个包含8个元素的int数组,分别把数组元素设置为2的前8次幂。

#include<stdio.h>

int main(void) {
	int arr[8];
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
		int value = 1;
		for (int j = 0; j <= i; ++j)
			value *= 2;
		arr[i] = value;
	}
	int i = 0;
	do {
		printf("%d ", arr[i++]);
	} while (i < sizeof(arr) / sizeof(arr[0]));

	return 0;
}

输出

2 4 8 16 32 64 128 256
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 20412)已退出,代码为 0。
按任意键关闭此窗口. . .

示例14:创建两个double类型的数组,一个数组的值为用户输入的值,一个数组的值为第一个数组对应的元素的累积和,然后打印两个数组。

#include<stdio.h>

int main(void) {
	double arr1[8], arr2[8];
	for (int i = 0; i < 8; ++i) {
		printf("Enter a value: ");
		scanf_s("%lf", &arr1[i]);
		double sum = 0.;
		for (int j = 0; j <= i; ++j)
			sum += arr1[j];
		arr2[i] = sum;
	}
	for (int i = 0; i < 8; ++i)printf("%.3lf ", arr1[i]);
	printf("\n");
	for (int i = 0; i < 8; ++i)printf("%.3lf ", arr2[i]);
	return 0;
}

输出

Enter a value: 2.
Enter a value: 3.
Enter a value: 4.
Enter a value: 5.
Enter a value: 6.
Enter a value: 7.
Enter a value: 8.
Enter a value: 9.
2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000
2.000 5.000 9.000 14.000 20.000 27.000 35.000 44.000
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 29664)已退出,代码为 0。
按任意键关闭此窗口. . .

示例15:读取一行输入然后倒序打印。

#include<stdio.h>

int main(void) {
	char ch;
	char chs[256];
	int ind = 0;
	scanf_s("%c", &ch);
	while (ch != '\n') {
		chs[ind++] = ch;
		scanf_s("%c", &ch);
	}
	chs[ind] = '\0';
	for (int i = 0; i < ind; ++i)
		printf("%c", chs[ind - 1 - i]);
	return 0;
}

输出

Everything will be ok.
.ko eb lliw gnihtyrevE
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 3592)已退出,代码为 0。
按任意键关闭此窗口. . .

示例16:Daphne以10%的单利息投资100美元,Deirdre以5%的复合利息投资了100美元,计算需要多少年Deirdre的投资额会超过Daphne,并打印两人的投资额。

#include<stdio.h>

int main(void) {
	double d1 = 100., d2 = 100.;
	int years = 0;
	while (d1 >= d2) {
		d1 += 10.;
		d2 += d2 * 0.05;
		years++;
	}
	printf("%d Years Later, Daphne: %lf ,Deirdre: %lf.", years, d1, d2);

	return 0;
}

输出

27 Years Later, Daphne: 370.000000 ,Deirdre: 373.345632.
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 26064)已退出,代码为 0。
按任意键关闭此窗口. . .

示例17:Chunkie Lucky赢得了100万美元(税后),它把奖金存入年利率8%的账户,在每年最后一天取出10万美元,计算多少年后他会取完账户的钱。

#include<stdio.h>

int main(void) {
	double money = 100;
	int years = 0;
	while (money >= 10) {
		money += money * 0.08;
		money -= 10;
		years++;
	}
	printf("%d Years Later.", ++years);

	return 0;
}

输出

21 Years Later.
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 27168)已退出,代码为 0。
按任意键关闭此窗口. . .

示例18:Rabnud博士加入了一个社交圈,起初有5个朋友,第N周少了N个朋友,然后剩下的数量翻倍,打印他每周朋友的数量,直到这个数字超过150。

#include<stdio.h>

int main(void) {
	int num = 5;
	int weeks = 0;
	while (num <= 150) {
		weeks++;
		num -= weeks;
		num *= 2;
		printf("第 %d 周,Rabnud博士的朋友数为 %d。\n", weeks, num);
	}

	return 0;
}

输出

1 周,Rabnud博士的朋友数为 8。
第 2 周,Rabnud博士的朋友数为 12。
第 3 周,Rabnud博士的朋友数为 18。
第 4 周,Rabnud博士的朋友数为 28。
第 5 周,Rabnud博士的朋友数为 46。
第 6 周,Rabnud博士的朋友数为 80。
第 7 周,Rabnud博士的朋友数为 146。
第 8 周,Rabnud博士的朋友数为 276。

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 17652)已退出,代码为 0。
按任意键关闭此窗口. . .

分支和跳转–示例(均来自课后习题)

示例1:读取输入直到#字符结束,报告读取的空格数、换行数和所有其它的字符数量。

#include<stdio.h>
#include<ctype.h>

int main(void) {
	int space = 0, lines = 0, others = 0;
	char ch;
	while ((ch=getchar())!='#')
	{
		if (ch==' ')
			space++;
		else if (ch == '\n')
			lines++;
		else
			others++;
	}
	printf("空格数:%d,行数:%d,其它字符:%d ", space, lines, others);

	return 0;
}

输出

asdhfaheriuhsjf asdfjasd fas fas dfas d
asdf af adf asdf arf
asd fasd fas dfas f
aw sasd fas  asdf
#
空格数:18,行数:4,其它字符:78
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 38968)已退出,代码为 0。
按任意键关闭此窗口. . .

示例2:读取输入直到#字符为止,打印每个输入的字符及对应的ASCII码,每行打印八个。

#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main(void) {
	char ch;
	char chs[255];
	int ind = 0;
	while ((ch = getchar()) != '#') {
		if(!isspace(ch))
			chs[ind++] = ch;
	}
	chs[ind] = '\0';
	for (int i = 0; i < strlen(chs); ++i) {
		if (i % 8 == 0)
			printf("\n");
		printf(" %c- %d ,", chs[i], chs[i]);
	}
	
	return 0;
}

输出

abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
asfakjdls fajfojnasfas dfasd fadfj; akrjowire j
#

 a- 97 , b- 98 , c- 99 , d- 100 , e- 101 , f- 102 , g- 103 , h- 104 ,
 i- 105 , j- 106 , k- 107 , l- 108 , m- 109 , n- 110 , o- 111 , p- 112 ,
 q- 113 , r- 114 , s- 115 , t- 116 , u- 117 , v- 118 , w- 119 , x- 120 ,
 y- 121 , z- 122 , A- 65 , B- 66 , C- 67 , D- 68 , E- 69 , F- 70 ,
 G- 71 , H- 72 , I- 73 , J- 74 , K- 75 , L- 76 , M- 77 , N- 78 ,
 O- 79 , P- 80 , Q- 81 , R- 82 , S- 83 , T- 84 , U- 85 , V- 86 ,
 W- 87 , X- 88 , Y- 89 , Z- 90 , a- 97 , s- 115 , f- 102 , a- 97 ,
 k- 107 , j- 106 , d- 100 , l- 108 , s- 115 , f- 102 , a- 97 , j- 106 ,
 f- 102 , o- 111 , j- 106 , n- 110 , a- 97 , s- 115 , f- 102 , a- 97 ,
 s- 115 , d- 100 , f- 102 , a- 97 , s- 115 , d- 100 , f- 102 , a- 97 ,
 d- 100 , f- 102 , j- 106 , ;- 59 , a- 97 , k- 107 , r- 114 , j- 106 ,
 o- 111 , w- 119 , i- 105 , r- 114 , e- 101 , j- 106 ,
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 8076)已退出,代码为 0。
按任意键关闭此窗口. . .

示例3:读取整数直到用户输入0结束,打印输入的偶数个数和偶数的平均值,奇数个数和奇数的平局值。

#include<stdio.h>

int main(void) {
	int value, odd = 0, even = 0, odd_s = 0, even_s = 0;
	scanf_s("%d", &value);
	while (value!=0)
	{
		if (value % 2) {
			odd++;
			odd_s += value;
		}
		else {
			even++;
			even_s += value;
		}
		scanf_s("%d", &value);
	}
	printf("The number of odd: %d, mean:%.1f \nand the number of even: %d , mean: %.1f ", odd, (float)odd_s / (float)odd, even, (float)even_s / (float)even);

	return 0;
}

输出

1
2
3
4
5
6
0
The number of odd: 3, mean:3.0
and the number of even: 3 , mean: 4.0
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 17964)已退出,代码为 0。
按任意键关闭此窗口. . .

示例4: 读取输入直到#结束吗,用感叹号代器句号,两个感叹号代替感叹号,最后报告进行了多少次替换。

#include<stdio.h>

int main(void) {
	char ch;
	char chs[225];
	int index = 0, times = 0;
	while((ch = getchar()) != '#') {
		if (ch == '!') {
			chs[index++] = '!';
			chs[index++] = '!';
			times++;
		}
		else if (ch == '.') {
			chs[index++] = '!';
			times++;
		}
		else
			chs[index++] = ch;
	}
	chs[index] = '/0';
	for (int i = 0; i < index; ++i)
		putchar(chs[i]);
	printf("\n%d 次替换", times);

	return 0;
}

输出

adfhuiwejhjajhdf.
asdf.a
df.a
s.
!!
!
#
adfhuiwejhjajhdf!
asdf!a
df!a
s!
!!!!
!!

7 次替换
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 19580)已退出,代码为 0。
按任意键关闭此窗口. . .

示例5:用switch重写示例4。

#include<stdio.h>

int main(void) {
	char ch;
	char chs[225];
	int index = 0, times = 0;
	while((ch = getchar()) != '#') {
		switch (ch)
		{
		case '!':
			chs[index++] = '!';
			chs[index++] = '!';
			times++;
			break;
		case '.':
			chs[index++] = '!';
			times++;
			break;
		default:
			chs[index++] = ch;
			break;
		}
	}
	chs[index] = '/0';
	for (int i = 0; i < index; ++i)
		putchar(chs[i]);
	printf("\n%d 次替换", times);

	return 0;
}

输出

testtest.
The World!
.
!
#
testtest!
The World!!
!
!!

4 次替换
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 17836)已退出,代码为 0。
按任意键关闭此窗口. . .

示例6:读取输入直到#,打印ei出现的次数。

#include<stdio.h>

int main(void) {
	char ch1,ch2;
	int times = 0;
	ch1 = getchar();
	while((ch2 = getchar()) != '#' &&ch1!='#') {
		if (ch1 == 'e' && ch2 == 'i')
			times++;
		ch1 = ch2;
	}
	printf("ei出现了 %d 次", times);

	return 0;
}

输出

ei1a wejfdsjfoiwejei asdjkfaksdjfei asdfjaskei
aei aei s
#
ei出现了 6 次
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 6528)已退出,代码为 0。
按任意键关闭此窗口. . .

示例7:输入一周工作的小时数,打印工资总额、税收和净收入。

#include<stdio.h>
#define VALUE 10.0f
#define TIMES 1.5f

int main(void) {
	float time;
	printf("请输入一周工作的小时数:");
	scanf_s("%f", &time);
	time =(time>40)? 40.0f + (time - 40.0f) * TIMES:time;
	float money = VALUE * time;
	printf("工资总额:%f",money);
	float taxes;
	if (money > 450) 
		taxes = (money - 450.f) * 0.25f+150.f*0.2f+300.f*0.15f;
	else if (money > 300) 
		taxes = (money - 300.f) * 0.2f + 300.f * 0.15f;
	else
		taxes = money * 0.15f;
	printf("\n税金:%.1f,净收入:%.1f", taxes, money - taxes);

	return 0;
} 

输出

请输入一周工作的小时数:60
工资总额:700.000000
税金:137.5,净收入:562.5
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 43992)已退出,代码为 0。
按任意键关闭此窗口. . .

示例8:修改示例7,使用户可以自己选择工资等级。

#include<stdio.h>
#define VALUE1 8.75f
#define VALUE2 9.33f
#define VALUE3 10.0f
#define VALUE4 11.2f
#define TIMES 1.5f

int main(void) {
	float time,v;
	printf("*******************************************************************");
	printf("\nEnter the number corresponding to the desired pay rate or action: ");
	printf("\n1) $%.2f/hr                           2) $%.2f/hr", VALUE1, VALUE2);
	printf("\n3) $%.2f/hr                          4) $%.2f/hr", VALUE3, VALUE4);
	printf("\n5) quit\n");
	printf("*******************************************************************\n");
	int selecteditem;
	int items[] = { VALUE1,VALUE2,VALUE3,VALUE4 };
	scanf_s("%d", &selecteditem);
	while (selecteditem > 0 && selecteditem < 5) {
		printf("请输入一周工作的小时数:");
		scanf_s("%f", &time);
		time = (time > 40) ? 40.0f + (time - 40.0f) * TIMES : time;
		float money = items[selecteditem-1] * time;
		printf("工资总额:%f", money);
		float taxes;
		if (money > 450)
			taxes = (money - 450.f) * 0.25f + 150.f * 0.2f + 300.f * 0.15f;
		else if (money > 300)
			taxes = (money - 300.f) * 0.2f + 300.f * 0.15f;
		else
			taxes = money * 0.15f;
		printf("\n税金:%.1f,净收入:%.1f\nagain: ", taxes, money - taxes);
		scanf_s("%d", &selecteditem);
	}
	
	return 0;
} 

输出

*******************************************************************
Enter the number corresponding to the desired pay rate or action:
1) $8.75/hr                           2) $9.33/hr
3) $10.00/hr                          4) $11.20/hr
5) quit
*******************************************************************
2
请输入一周工作的小时数:45
工资总额:427.500000
税金:70.5,净收入:357.0
again: 4
请输入一周工作的小时数:50
工资总额:605.000000
税金:113.8,净收入:491.3
again: 0

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 14012)已退出,代码为 0。
按任意键关闭此窗口. . .

示例9:输入一个正整数,打印所有小于等于它的素数。

#include<stdio.h>

int main(void) {
	unsigned value;
	printf("输入正整数: ");
	scanf_s("%u", &value);
	while (value) {//value!=0
		if (value == 1)
			printf("小于等于该数的素数有:1\n");
		else if (value == 2)
			printf("小于等于该数的素数有:1, 2\n");
		else {
			printf("小于等于该数的素数有:1, 2");
			for (int i = 3; i <= value; ++i) {
				_Bool isprimer = 1;//true;
				for (int j = 2; j < i; ++j) {
					if (i % j == 0) {
						isprimer = 0;
						break;
					}
				}
				if (isprimer)
					printf(", %d", i);
			}
		}
		printf("\n输入正整数: ");
		scanf_s("%u", &value);
	}
	

	return 0;
} 

输出

输入正整数: 20
小于等于该数的素数有:1, 2, 3, 5, 7, 11, 13, 17, 19
输入正整数: 30
小于等于该数的素数有:1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
输入正整数: 100
小于等于该数的素数有:1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
输入正整数: 100
小于等于该数的素数有:1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
输入正整数: 1000
小于等于该数的素数有:1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
输入正整数: 0

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 39020)已退出,代码为 0。
按任意键关闭此窗口. . .

示例10:让用户指定缴纳金的种类和应缴纳收入,然后计算税金。

#include<stdio.h>

int main(void) {
	printf("-------------------------------------------------------\n");
	printf("请输入缴纳税金的种类: ");
	printf("\n1) 单身                 2)户主");
	printf("\n3) 已婚、共有           4)已婚、离异\n");
	printf("-------------------------------------------------------\n");
	int se;
	scanf_s("%d", &se);
	double salary,texes;
	int tex[4] = { 17850,23900,29750,14875 };
	while (se > 0 && se < 5) {
		printf("请输入收入:");
		scanf_s("%lf", &salary);
		texes = salary > tex[se - 1] ? (double)tex[se - 1] * 0.15 + (salary - (double)tex[se - 1]) * 0.28 : salary * 0.15;
		printf("税金为:%lf\n", texes);
		printf("Again: ");
		scanf_s("%d", &se);
	}
	

	return 0;
} 

输出

-------------------------------------------------------
请输入缴纳税金的种类:
1) 单身                 2)户主
3) 已婚、共有           4)已婚、离异
-------------------------------------------------------
1
请输入收入:22222.
税金为:3901.660000
Again: 3
请输入收入:33333.
税金为:5465.740000
Again: 0

C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 16084)已退出,代码为 0。
按任意键关闭此窗口. . .

示例11

#include<stdio.h>

int main(void) {
	char ch;
	int a_w = 0, b_w = 0, c_w = 0,value;
	printf("输入一个字母来订购一个商品:(a-洋蓟,b-甜菜,c-胡萝卜,q-退出)");
	while ((ch = getchar()) != 'q') {
		switch (ch)
		{
		case 'a':
			printf("输入洋蓟重量:");
			scanf_s("%d", &value);
			a_w += value;
			printf("洋蓟的总重为:%d\n", a_w);
			printf("再输入一个字母来订购一个商品:");
			break;
		case 'b':
			printf("输入甜菜重量:");
			scanf_s("%d", &value);
			b_w += value;
			printf("甜菜的总重为:%d\n", b_w);
			printf("再输入一个字母来订购一个商品:");
			break;
		case 'c':
			printf("输入胡萝卜重量:");
			scanf_s("%d", &value);
			c_w += value;
			printf("胡萝卜的总重为:%d\n", c_w);
			printf("再输入一个字母来订购一个商品:");
			break;
		default:
			break;
		}
	}
	float sum = 2.05f * (float)a_w + 1.15f * (float)b_w + 1.09f * (float)c_w;
	float discount= sum >= 100 ? sum * 0.05f : 0.f;
	float t_w = a_w + b_w + c_w;
	float extra= t_w <= 5 ? 6.5f : t_w <= 20 ? 14.f : 14.f + (t_w - 20.f) * 0.5f;
	float sums =sum-discount+extra;
	printf("洋蓟售价:2.05 $/磅,甜菜:1.15 $/磅,胡萝卜:1.09 $/磅\n");
	printf("总计:\n总重量:%.1f\n洋蓟总费用:%.1f $\n甜菜总费用:%.1f $\n胡萝卜总费用:%.1f $\n", t_w, 2.05f * (float)a_w, 1.15f * (float)b_w, 1.09f * (float)c_w);
	printf("订单总费用:%.3f $\n折扣:%.3f $\n运费和包装费:%.3f $\n总费用:%.3f $", sum, discount, extra, sums);
	printf("\n购物愉快!");

	return 0;
} 

输出

输入一个字母来订购一个商品:(a-洋蓟,b-甜菜,c-胡萝卜,q-退出)a
输入洋蓟重量:22
洋蓟的总重为:22
再输入一个字母来订购一个商品:b
输入甜菜重量:1
甜菜的总重为:1
再输入一个字母来订购一个商品:b
输入甜菜重量:22
甜菜的总重为:23
再输入一个字母来订购一个商品:c
输入胡萝卜重量:2
胡萝卜的总重为:2
再输入一个字母来订购一个商品:c
输入胡萝卜重量:6
胡萝卜的总重为:8
再输入一个字母来订购一个商品:c
输入胡萝卜重量:9
胡萝卜的总重为:17
再输入一个字母来订购一个商品:1
1
a
输入洋蓟重量:1
洋蓟的总重为:23
再输入一个字母来订购一个商品:q
洋蓟售价:2.05 $/磅,甜菜:1.15 $/磅,胡萝卜:1.09 $/磅
总计:
总重量:63.0
洋蓟总费用:47.1 $
甜菜总费用:26.4 $
胡萝卜总费用:18.5 $
订单总费用:92.130 $
折扣:0.000 $
运费和包装费:35.500 $
总费用:127.630 $
购物愉快!
C:\Users\xhh\Source\Repos\c_study_1\Debug\c_study_1.exe (进程 36644)已退出,代码为 0。
按任意键关闭此窗口. . .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值