vimer linux kernel 爱好者

c编程参考循环

2018-09-22

这一部分是简单题目,初次可以写的乱一些。没有仔细考虑,有错误还望指正。

1 计算 1! + 2! +…+10!

下面第一个程序太臃肿,还不好理解,可以参考第二种方案。

程序一:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* 求 10! + 9! + .. + 1! = ? */

int main()
{
	int i,j;
	int factorial = 1, sum = 0;
	int temp = 1;
	for (i = 1; i <= 10; i++){
		sum += temp;

		for(j = 10 - i + 1; j >= 1; j--){
			factorial = j * factorial;
		}
		temp = factorial;
		printf("the %dth factorial is %d\n", i, factorial);
		factorial = 1;
	}

	printf("The sum of 1! + 2! + 3! +...+ 10!=%d\n", sum);
}

程序二:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
	int i,j,sum = 0, c = 1;
	for(i = 1; i <= 10; i++){
		c = i * c;
		sum = sum + c;

	}
	printf("1! + 2! + 3! + ...+ 10!= %d\n",sum);
}

2 计算Sn = a + aa + aaa +…+aaa..a(n个a)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
/* 输入n 个 a, 计算 a + aa + aaa + ... + aaaaaa(n个a) = ? , 此时n = 6*/
int main()
{
	int n, a;
	printf("请输入n 和a的值:\n");
	scanf("%d %d", &n, &a);
	int i, j, sum = 0, per_sum = 0;
	for(j = n; j > 0; j--){
		/* 下面这个for循环只是运行了最后一个的数字,比如3333,前面的没有算进来 */
		per_sum = 0;
		for(i = j; i >= 1; i--){
			per_sum += a*pow(10, i-1);
	//		printf("The %dth sum is %d\n", i, per_sum);

		}
		sum += per_sum;
//		printf("the a + aa +...+ = %d\n",sum);
	}
	printf("the a + aa +...+ = %d\n", sum);
}

3 乒乓球比赛

甲队为a b c,乙队为x, y, z,且a不与x比, c不和x,y比,求可能的比赛名单。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* a 的ascii码是97  x 是120 ...*/
int main()
{
	int a = 97, x = 120;
	for(a = 97; a <= 99; a++){
		for(x = 120; x <= 122; x++){
			if(a == 97 && x == 120) continue;
			if(a == 99 && x == 120) continue;
			if(a == 99 && x == 121) continue;
			printf("对阵的双方可以%c VS %c\n", a, x);
		}
		printf("\n");
	}

}

4 输入一行字符串,分别统计出其中的英文字符、空格、数字和其他字符(以换行符为结束标志)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*由于教材的编排原因,这个时候还没有学习数组,故使用p80页的二大题
* 第一小题的例子
*/

/* 这里的技巧就是通过判断输入的字符是否为特定字符从而结束判断,比如'\n' */
int main()
{
	int zimu = 0, spaces = 0, nums = 0, others = 0;
	char c;
	printf("请输入一串字符串,以换行结尾\n");
	c = getchar();
	while(c != '\n'){
		if(c >= 65 && c <= 90 || c >= 97 && c <= 122){
		/* 字母在A-Z, a-z之间*/
			zimu++;
		} else if(c == ' ')
			spaces++;
		else if (c >= 48 && c <= 57)
			nums++;
		else
			others++;
		c = getchar();
	}
	printf("统计情况如下:字母:%d 空格: %d, 数字: %d 其他: %d\n", zimu, spaces, nums, others);

}

分解因式

输入p,q值, q>0, p>0,试分析能否分解,比如,x^2+5x+6=0(p=5, q=6),问能否分解。

int main()
{
	int p,q;// p > 0, q >0
	int a, b;
	int flag = 0; // 标志变量
	scanf("%d %d", &p, &q);
	for(a = 1; a < sqrt(q); a++){
		if(q % a == 0){
			b = q/a;
			if(a + b == p){
				flag = 1;
				break;
			}
		}
	}
	if(flag)
		printf("p,q 可以分解,其两个根分别为x1=-%d,x2=-%d\n", a, b);
	else
		printf("不可以分解\n");

}

上一篇 shell的cut用法

Comments

Content