以c为单位打印一个数字

时间:2013-11-21 06:57:31

标签: c

我有号码5678

我想要显示号码如下

5678
678
78
8

我怎么能在c ??

我完成了这个

int n = 5678;

for(int i=n; i >= 1; --i)
{
    for(int j=1; j <= i; ++j)
  {

       print("%d",j);

  }

   print("\n")
}

2 个答案:

答案 0 :(得分:5)

首先“stringify” int,然后你可以使用一个字符串指针:

int main()
{
    int n = 5678;
    char *str_p, str[10];//declare a char pointer, and an array of 10 chars
    sprintf(str, "%d", n);//initializes str to {'5','6','7','8','\0'}
    str_p = &str[0];//init pointer to start of string, str_p = str; works, too
    while(*str_p != '\0')
    {//while pointer doesn't point to end of string:
        printf("%s\n", str_p);//print string str_p points to
        str_p++;//shift pointer, to point to next char in string
    }
    return 0;
}

结果输出,如您所见in this codepad

5678
678
78
8

非常简单,真的 诀窍是str_p++。起初,当我学习指针时,我发现这很令人困惑。但它真的很简单。将指针想象成日历上的红色塑料方形物:您可以将它滑过当天的任何日期:

MAY:
_____________________________
|   |   |   |   |   |___|   |
| 1 | 2 | 3 | 4 | 5 ||6|| 7 |
|___|___|___|___|___|---|___|

这意味着它是五月六日。是的,如果我们将它转​​换为C中的指针+数组,我们会有类似的东西:

int may[31] = {1,2,3,4,5,6,7,8,9,...};
int *today = &may[5];//zero indexed

将红色方块滑动到第二天(今天+ 1 ==明天)的动作在逻辑上写成:

today++;//or today += 1

这就是说:

          today + 1: [] =>[]//shift the red square-thingy
_____________________________
|   |   |   |   |   |   |___|
| 1 | 2 | 3 | 4 | 5 | 6 ||7||
|___|___|___|___|___|___|---|

所以如果我那么写:

today--;

同样的逻辑适用,今天又回到6 ...去商店,如果你觉得有必要想象这个,请购买其中一个日历...
假设您想要更改指针指向的值?好吧,坚持使用相同的类比(滑块超过某个值),你必须用一只手将滑块固定到位,另一只手,你可以使用它下面的工具。在您的代码中,这由隐式*运算符反映。可以把它想象成一个引脚,在你指向它的任何东西时将指针固定到位:

(*today)++;//or *today++;, both operators have the same precedence

真的,真的,真的,真的很简单......好吧,不,不是:)但是9/10次你使用指针,这种思维方式有效

顺便说一句:使用str_p = str;,我认为更合乎逻辑,而且效率更高,但编译器可能会将两个语句优化为同一个东西。仍然是Here's another codepad, to prove both do the same thing

现在,最后,一个更通用的方法,它将使用可变长度的数量,动态分配字符串所需的内存,并再次释放它:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, len, n = 5678;
    char *str_p = NULL;
    int digitCount(int in);
    len = digitCount(n);//how many chars do we need to allocate?
    str_p = calloc(len, sizeof(char));//allocate string, calloc inits memory to 0
    len--;//avoid printing empty string at the end
    sprintf(str_p, "%d", n);//set string in memory
    for(i=0;i<len;++i) printf("%s\n", str_p + i);//print string, increment pointer by i
    free(str_p);//deallocate string memory
    return 0;
}

int digitCount(int in)
{
    int count = 1;//1 for 0 terminating char
    while(in)
    {//as long as in/10 (being an int, this will eventually become 0 ==> false)
        in /= 10;
        ++count;//add 1 digit to count
    }
    return count;
}

答案 1 :(得分:0)

int reversDigits(int num)
{
    int rev_num = 0;
    while(num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}

int main()
{
int num=5678;
int rev=reversDigits(num);
while(rev)
{

printf("%d "reversDigits(rev));
printf("\n");
rev=rev/10;

}
}