轉載自:https://blog.csdn.net/xia0liang/article/details/53157455
【程序27】
題目:利用遞歸函數調用方式,將所輸入的5個字符,以相反順序打印出來。
1.程序分析:
2.程序源代碼:(下面代碼運行後,輸入5,接着輸入五個字符,結果只輸出前四個字符的相反順序)
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int reverse(int n)
{
char next;
if (n <= 1)
{
next = getchar();
printf("\n\0: ");
putchar(next);
}
else
{
next = getchar();
reverse(n - 1);
putchar(next);
}
return 0;
}
int main()
{
//SetConsoleOutputCP(437);
int i;
scanf("%d", &i);
printf("\40: ");//輸出一個冒號
reverse(i);
system("pause");
}
【程序28】
題目:有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數,他說比第3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最後問第一個人,他說是10歲。請問第五個人多大?
1.程序分析:利用遞歸的方法,遞歸分爲回推和遞推兩個階段。要想知道第五個人歲數,需知道第四人的歲數,依次類推,推到第一人(10歲),再往回推。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int age(int n)
{
int c;
if (n == 1)//此處不可以寫成n=1,否則運行結果始終爲10
c = 10;
else
c = age(n - 1) + 2;
return c;
}
int main()
{
//SetConsoleOutputCP(437);
int i;
scanf("%d", &i);
printf("第%d個人的年齡爲:%d\n ", i,age(i));
system("pause");
}
【程序29】
題目:給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。
1. 程序分析:學會分解出每一位數
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
long a, b, c, d, e, x;
scanf("%ld", &x);
a = x / 10000; //分解出萬位
b = x % 10000 / 1000;//分解出千位
c = x % 1000 / 100; //分解出百位
d = x % 100 / 10; //分解出十位
e = x % 10; //分解出個位
if (a != 0)
printf("這是個五位數,%ld%ld%ld%ld%ld\n", e, d, c, b, a);
else if (b != 0)
printf("這是個四位數,%ld%ld%ld%ld\n", e, d, c, b);
else if (c != 0)
printf("這是個三位數,%ld%ld%ld\n", e, d, c);
else if (d != 0)
printf("這是個兩位數,%ld%ld\n", e, d);
else if (e != 0)
printf("這是個一位數,%ld\n", e);
system("pause");
}
【程序30】
題目:一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。
1.程序分析:同29例
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
long a, b, d, e, x;
scanf("%ld", &x);
a = x / 10000; //分解出萬位
b = x % 10000 / 1000;//分解出千位
//c = x % 1000 / 100; //分解出百位
d = x % 100 / 10; //分解出十位
e = x % 10; //分解出個位
if (a == e&&b == d)
printf("這是一個迴文數\n");
else
printf("這不是一個迴文數\n");
system("pause");
}
【程序31】
題目:請輸入星期幾的第一個字母來判斷一下是星期幾,如果第一個字母一樣,則繼續判斷第二個字母。
1.程序分析:用情況語句比較好,如果第一個字母一樣,則判斷用情況語句或if語句判斷第二個字母。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
char letter;
printf("please input the first letter of someday\n");
while ((letter = getchar()) != 'y')//當所按字母爲Y時結束
{
switch (letter)
{
case 'M':
printf("Monday\n");
break;
case 'T':
printf("please input the second letter of someday\n");
if ((letter = getchar()) == 'u')
printf("Tuesday\n");
else if ((letter = getchar()) == 'h')
printf("Thursday\n");
else
printf("dataerror\n");
break;
case 'W':
printf("Wednesday\n");
break;
case 'F':
printf("Friday\n");
break;
case 'S':
printf("please input the second letter of someday\n");
if ((letter = getchar()) == 'a')
printf("Saturday\n");
else if ((letter = getchar()) == 'u')
printf("Sunday\n");
else
printf("dataerror\n");
break;
default:
printf("\n");
}
}
system("pause");
}