C語言編程練習(七)(vs2015)

轉載自:https://blog.csdn.net/xia0liang/article/details/53157455

【程序32】
題目:Press any key to change color, do you want to tryit. Please hurry up!
1.程序分析:            
2.程序源代碼:(本代碼因爲VS裏面的conio.h文件裏沒有textbackground函數,所以直接貼原博主代碼)

#include "stdio.h"
#include "stdlib.h"
#include <conio.h>
int main()
{
	//SetConsoleOutputCP(437);
	int color;
	for (color = 0; color <= 8; color++)
	{
		textbackground(color);//設置文本的背景顏色
		cprintf("This is color %d\r\n", color);
		cprintf("Press any key to continue\r\n");
		getch();//輸入字符看不見
	}
	system("pause");
}

【程序33】
題目:求100以內的素數   
1.程序分析:
2.程序源代碼:

#include "stdio.h"
#include "stdlib.h"
#include <math.h>
#define N 101
int main()
{
	int i, j, line, a[N];
	for (i = 2; i < N; i++)
		a[i] = i;
	for(i=2;i<sqrt(N);i++)
		for (j = i + 1; j < N; j++)
		{
			if (a[i] != 0 && a[j] != 0)
				if (a[j] % a[i] == 0)
					a[j] = 0;
		}
	printf("\n");
	for (i = 2, line = 0; i < N; i++)
	{
		if (a[i] != 0)
		{
			printf("%5d", a[i]);
			line++;
		}
		if (line == 10)
		{
			printf("\n");
			line = 0;
		}
	}
	system("pause");
}
#include "stdio.h"
#include "stdlib.h"
#include <math.h>
int main()
{
	int i, j;
	for (i = 2; i < 100; i++)
	{
		for (j = 2; j < i; j++)
		{
			if (i%j == 0)
				break;
		}
		if (j >= i)
		{
			printf("%d\n", i);
		}
	}	
	system("pause");
}

【程序34】
題目:對10個數進行排序
1.程序分析:可以利用選擇法,即從後9個比較過程中,選擇一個最小的與第一個元素交換,下次類推,即用第二個元素與後8個進行比較,並進行交換。      
2.程序源代碼:(原博主的代碼錯誤,下面爲正確代碼。運行正確)

#include "stdio.h"
#include "stdlib.h"
#include <math.h>
#define N 10
int main()
{
	int i, j, min, tem, a[N];
	printf("please input ten num:\n");
	for (i = 0; i < N; i++)
	{
		printf("a[%d]=", i);
		scanf("%d", &a[i]);
	}
	printf("\n");
	for (i = 0; i < N; i++)
		printf("%5d", a[i]);
	printf("\n");
	//下面開始排序
	for (i = 0; i < N - 1; i++)
	{
		min = i;
		for (j = i + 1; j < N; j++)
		{
			if (a[min] > a[j])
			{
				tem = a[min];
				a[min] = a[j];
				a[j] = tem;
			}
		}	
	}
	//輸出結果
	printf("after sorted\n");
	for (i = 0; i < N; i++)
		printf("%5d", a[i]);
	system("pause");
}

【程序35】
題目:求一個3*3矩陣對角線元素之和
1.程序分析:利用雙重for循環控制輸入二維數組,再將a[i][i]累加後輸出。
2.程序源代碼:

#include "stdio.h"
#include "stdlib.h"
int main()
{
	long a[3][3], sum = 0;
	int i, j;
	printf("please input element:\n");
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			scanf("%ld", &a[i][j]);
		}	
	}
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			if ((i = j)||(i+j)==2)
			{
				sum = sum + a[i][j];
			}
		}
	}
	printf("對角線元素之和爲;%ld", sum);
	system("pause");
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章