本文介绍了插入数字之间的间隔用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么会去服用一些如 123456 并让它打印为 1 2 3 4 5 6


解决方案

由于'jamesdlin在他的评论中提到,GMAN的方法是有效的,但您需要将其存储在缓冲区中,才能在正确的打印出来为了(他的算法会打印出6 5 4 3 2 1输入123456)。在这一点上,我会说,这将是更简单,只是用sprintf为therefromhere在他的回答表明(如果这当然不是一个算法类分配)。

在我看来这样做将使用递归最简单的方式,这种方式可以打印出正确的顺序数字,而无需使用缓冲。

递归实现非常简单:

 无效PrintfRecursivly(INT数)
{
     如果(数℃,)
     {
       数* = -1;
       的printf( - );
     }
     如果(数大于10)
     {
        PrintfRecursivly(数/ 10);
        的printf();
     }     的printf(%d个,数10%);
}诠释的main()
{
   INT数= -78900456;
   PrintfRecursivly(数);   返回0;
}

输入:

Output:

EDIT: Thanks to Steve Jessop who suggested a correct algorithm for positive integers while I was away. I changed the above method to print out correctly for all ints (positive and negative), without the last space.

Please note that we can avoid checking for negative values in every recursion, by doing the check just once (in the main function or wherever) but I didn't write it because we would lose more on clarity than gain in performance.

这篇关于插入数字之间的间隔用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:15
查看更多