以c为单位打印一个数字
我的号码是5678
我想要显示如下编号
5678 678 78 8
我该怎么办?
我这样做了
int n = 5678; for(int i=n; i >= 1; --i) { for(int j=1; j <= i; ++j) { print("%d",j); } print("\n") }
首先“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; }
如您在此键盘中看到的结果输出是:
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 …去商店,如果你觉得有必要想象这个,请购买其中一个日历……
假设您想要更改指针指向的值? 好吧,坚持相同的类比(滑块超过某个值),你必须用一只手将滑块固定到位,另一只手,你可以使用它下面的内容。 在您的代码中,这由inderection *
运算符反映。 将它想象为一个引脚,在你指向它所指向的任何东西时将指针固定到位:
(*today)++;//or *today++;, both operators have the same precedence
它真的,真的,真的非常简单……好吧,不,不是:)但是9/10次你使用指针,这种思维方式有效
BTW:使用str_p = str;
是的,我认为更合乎逻辑,而且效率更高,但编译器可能会将两个语句优化为同一个东西。 还在这里是另一个键盘,以certificate两者都做同样的事情
现在,结束一种更通用的方法,它将使用多个可变长度,动态分配字符串所需的内存,并再次释放它:
#include #include 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 false) in /= 10; ++count;//add 1 digit to count } return count; }
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; } }