我有号码 5678
我想要显示如下编号
5678
678
78
8
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
我这样做了
int n = 5678;
for(int i=n; i >= 1; --i)
{
for(int j=1; j <= i; ++j)
{
print("%d",j);
}
print("\n")
}
Run Code Online (Sandbox Code Playgroud)
首先"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;
}
Run Code Online (Sandbox Code Playgroud)
如您在此键盘中看到的结果输出是:
5678
678
78
8
Run Code Online (Sandbox Code Playgroud)
很简单,真的.
诀窍是str_p++.起初,当我学习指针时,我发现这很令人困惑.但它真的很简单.将指针想象成日历上的红色塑料方形物:您可以将它滑过当天的任何日期:
MAY:
_____________________________
| | | | | |___| |
| 1 | 2 | 3 | 4 | 5 ||6|| 7 |
|___|___|___|___|___|---|___|
Run Code Online (Sandbox Code Playgroud)
这意味着它是五月六日.是的,如果我们将它转换为C中的指针+数组,我们会有类似的东西:
int may[31] = {1,2,3,4,5,6,7,8,9,...};
int *today = &may[5];//zero indexed
Run Code Online (Sandbox Code Playgroud)
将红色方块滑动到第二天(今天+ 1 ==明天)的动作在逻辑上写成,如下所示:
today++;//or today += 1
Run Code Online (Sandbox Code Playgroud)
这就是说:
today + 1: [] =>[]//shift the red square-thingy
_____________________________
| | | | | | |___|
| 1 | 2 | 3 | 4 | 5 | 6 ||7||
|___|___|___|___|___|___|---|
Run Code Online (Sandbox Code Playgroud)
所以如果我那么写:
today--;
Run Code Online (Sandbox Code Playgroud)
相同的逻辑适用,今天回到6 ...去商店,如果你觉得需要可视化这个日历购买其中一个......
假设你想要改变指针所指向的值?好吧,坚持使用相同的类比(滑块超过某个值),你必须用一只手将滑块固定到位,另一只手,你可以使用它下面的工具.在您的代码中,这由inderection *运算符反映.将它想象为一个引脚,将指针固定到位,同时处理它指向的任何内容:
(*today)++;//or *today++;, both operators have the same precedence
Run Code Online (Sandbox Code Playgroud)
它真的,真的,真的是那么简单......好吧,不,不是:)但是9/10次你使用指针,这种思维方式有效
BTW:使用str_p = str;is,我认为更合乎逻辑,而且效率更高,但编译器可能会优化两个语句到同一个东西.还有这是另一个键盘,以证明两者都做同样的事情
现在,最后,一个更通用的方法,它将使用多个可变长度,动态分配字符串所需的内存,并再次释放它:
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1259 次 |
| 最近记录: |