递归输出整数(C 语言版)

好久没有写过 C 语言的代码了,大一上半学期必修课有 C 语言,不过现在大三,因为一直没有写过所以忘得也差不多了,这一段时间想补一补数据结构的知识,去图书馆借了本 C 语言版的《数据结构与算法分析》,也巩固一下 C 语言。

小小练手的题目:说是有一个正整数 n ,写一个递归算法来输出 n 。

不得不说,偶犯了一个“愚蠢”的错误,来看看一开始写的代码:

#include "stdio.h"
int main()
{
	void printOut(unsigned int n)
	{
		printf("%d", n % 10);
		if(n >= 10)
		{
			printOut(n / 10);
		}
	}
	printOut(1234);
}

很神奇吧?!我也不知道我为啥写出个这个一直报错的东东,怎么看都没错呀?!这是怎么一回事儿呢?最后查看了 C 语言函数调用的相关资料才知道:1:自定义函数需要先声明;2:自定义函数不能写在 main() 主函数里!唉~ 我这个 C 语言基础!估计也有可能是写 Javascript 写习惯了…改过来吧:

#include "stdio.h"
void printOut();   //声明自定义函数
int main()
{
	printOut(1234);   //函数调用
}
void printOut(unsigned int n)   //函数体
{
	if(n >= 10)
	{
		printOut(n / 10);
	}
	printf("%d", n % 10);
}

输出:1234

Tips: 要是想反序输出这个整数呢?其实只要调换一下语句顺序:

#include "stdio.h"
void printOut();   //声明自定义函数
int main()
{
	printOut(1234);   //函数调用
}
void printOut(unsigned int n)   //函数体
{
	printf("%d", n % 10);
	if(n >= 10)
	{
		printOut(n / 10);
	}
}

:->

posted @ 2010-10-15 00:24  无墨来点睛  Views(1603)  Comments(0Edit  收藏  举报