1. 程式人生 > >用c語言輸出菱形,水仙花數,

用c語言輸出菱形,水仙花數,

1.在螢幕上輸出一個菱形 上半段以中間數middle為中心,向左向右依次擴開,注意字串帶有‘\0’,所以要除二減一才是中間數。

//打印出一個菱形
#include <stdio.h>
#include <stdlib.h>
#define Breadth 8//最中間的寬度包括\0
#define Middle Breadth / 2-1
void prtdiamond(char diamond[],int x){
	int left;
	int right;
	char ch = '*';
	for (left = 0, right = 0; left < Middle+1; left++, right++){
		diamond[Middle - left] = ch;//向左列印
		diamond[Middle + right] = ch;//向右列印
		printf("%s\n", diamond);

	}//上半段菱形

	ch = ' ';
	for (left = Middle, right = Middle; left > 0; left--, right--){
		diamond[Middle - left] = ch;
		diamond[Middle + right] = ch;
		printf("%s\n", diamond);
	}
}
int main(){
	char diamond[Breadth] = "       ";//找中間注意\0的儲存
	prtdiamond(diamond, Middle);
	system("pause");
	return 0;
}

2.列印0-999的水仙花數 利用除法和取餘將三位數的百位,十位,個位分別提取出來,進行三次冪的和,判斷是否等於本身。

////////////////////////////////////////////
//輸出水仙花數,水仙花數是指一個 n 位數(n≥3 )
//它的每個位上的數字的 n 次冪之和等於它本身
///////////////////////////////////////////
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define cube 3
int IsArmstrong(int num){
	int hundred = num / 100;
	int ten = (num % 100)/10;
	int bit = num % 10;
	int sum = pow(hundred, cube) + pow(ten, cube) + pow(bit, cube);
	if (sum == num){
		return 1;
	}
	else{
		return 0;
	}
}
int main(){
	int count;
	for (count = 100; count < 1000; count++){
		if (IsArmstrong(count)){
			printf("%d\n", count);
		}
		//printf("%d\n", count);
	}
	system("pause");
	return 0;
}

3.求Sn=a+aa+aaa+aaaa+aaaaa的前5項之和,其中a是一個數字

//求Sn = a + aa + aaa + aaaa + aaaaa的前5項之和,其中a是一個數字
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int IsSn(int a){
	int sum = 0;
	int count;
	int before=0;
	for (count = 0; count < 5; count++){
		before = a *pow(10, count) + before;
		sum = before+ sum;
	}
	return sum;
}
int main(){
	printf("Enter 1-9 numbers :\n");
	int num;
	scanf("%d", &num);
	printf("Sn = a + aa + aaa + aaaa + aaaaa\n");
	printf("Sn = %d", IsSn(num));
	system("pause");
	return 0;
}