C语言练手小代码——four

1 在屏幕上输出以下图案:

      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
       *
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
//在屏幕上输出以下图案:
 //      *
 //     ***
 //    *****
 //   *******
 //  *********
 // ***********
 //*************
 // ***********
 //  *********
 //   *******
 //    *****
 //     ***
 //      *
int main(){
	//先打印上半部分
	int line = 7;
	int i = 0;
	for (i = 1; i <=line; i++){
		//打印空格
		int j = 0;
		for (j = 0; j <line - i; j++){
			printf(" ");
		}
		//打印*
		for (j = 0; j <2*i-1; j++){
			printf("*");
		}
		printf("\n");
	}
	//打印下半部分
	for (i = 1; i <line; i++){
		//打印空格
		int j = 0;
		for (j = 0; j <i; j++){
			printf(" ");
		}
		//打印*
		for (j = 0; j <2 *(line-1-i)+1; j++){//?公式想不到
			printf("*");
		}
		printf("\n");
	}
	system("pause");
	return 0;
}

运行结果:
2.求出0~999之间的所有“水仙花数”并输出。(要特别注意局部变量和全局变量的使用)
/*
在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),是指一N位数,其各个数之N次方和等于该数。
例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。
*/
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
int main(){
	int i = 0;
	for (i = 0; i <1000; i++){
		double num = 1;
		int temp = i;
		while (temp / 10){//先判断是几位数
			num++;
			temp = temp / 10;
		}
	   temp = i;
	   int count = 0;
		while (temp){//对每一位求对应次方之和
			count = count +pow(temp%10, num);
			temp = temp / 10;
		}
		if (count == i){
			printf("%d ", i);
		}
	}
	system("pause");
	return 0;
}
运行结果:

3. 求Sn=a+aa+aaa+aaaa+aaaaa的前5项之和,其中a是一个数字,例如:2+22+222+2222+22222
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
//求Sn = a + aa + aaa + aaaa + aaaaa的前5项之和,其中a是一个数字,例如:2 + 22 + 222 + 2222 + 22222
int main(){
	int a = 2;
	int i = 1;
	int sum = 0;
	int temp = 0;
	for (i = 0; i <5; i++){
		temp = temp * 10 + a;//temp每次过来得到的是每一项的值
		sum = sum+temp;//累加每一项的值
	}
	printf("%d ", sum);
	system("pause");
	return 0;
}

运行结果:

4.编写一个程序,它从标准输入读取C源代码,并验证所有的花括号都正确的成对出现。
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
//编写一个程序,它从标准输入读取C源代码,并验证所有的花括号都正确的成对出现。
int main(){
	char ch = 0;
	int count = 0;
	while ((ch = getchar()) != EOF){//EOF--输入Ctrl+z结束输入
		if ( '{'==ch){
			count++;
		}
		else if (ch == '}'&&count == 0){//}}{{特殊情况
			printf("不匹配!");
			system("pause");
			return 0;
		}
	   else if ('}'==ch){
			count--;
		}
		
	}
	if (0 == count){
		printf("匹配!");
	}
	else{
		printf("不匹配!");
	}
	system("pause");
	return 0;
}
运行结果:(三种情况测试用例)


猜你喜欢

转载自blog.csdn.net/superwangxinrui/article/details/79952574