插入数字之间的间隔用C [英] Inserting spaces between digits in C

查看:87
本文介绍了插入数字之间的间隔用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;
}

输入:


  

-78900456


输出:


  -  7 8 9 0 0 4 5 6 


修改:感谢史蒂夫·杰索普谁建议为正整数一个正确的算法,而我离开。我改变了上面的方法正确打印出所有的整数(正面和负面的),没有最后的空间。

请注意,我们才能避免在每一个递归检查负值,做检查只有一次(在主函数或其它地方),但我没写,因为我们会失去更多的清晰度比的性能​​增益。

How would I go about taking a number like 123456 and having it print as 1 2 3 4 5 6?

解决方案

As 'jamesdlin' has mentioned in his comment, GMan's approach would work, however you will need to store it in a buffer in order to print out in the correct order (his algorithm would print out "6 5 4 3 2 1" for input 123456). At this point I'd say that it would be much simpler to just use sprintf as 'therefromhere' suggested in his answer (if this is not an algorithm class assignment of course).

In my opinion the simplest way to do it would be using recursion, this way you can print out digits in the right order without using buffers.

The recursive implementation is very simple:

void PrintfRecursivly(int number)
{
     if (number < 0) 
     {
       number *= -1;
       printf("- ");           
     }
     if (number > 10) 
     {
        PrintfRecursivly(number / 10);
        printf(" ");
     }

     printf("%d", number % 10);     
}

int main()
{
   int number = -78900456;
   PrintfRecursivly(number);

   return 0;
}

Input:

-78900456

Output:

- 7 8 9 0 0 4 5 6

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆