为什么printf("the value of str is \"%llu\"\n", str[0]);
不返回数组str中第一个数字的值?
当我尝试其他索引值(1,2,3)时,是否返回预期值?
通知任何帮助。刚开始学c。
#include <stdio.h>
int main()
{
// a will hold the number
unsigned long long int a=548763,i=0;
// str will hold the result which is the array
unsigned long long int str[20]= {};
// first we need to see the length of the number a
unsigned long long int b=a;
while(b>=10)
{
b=b/10;
i++;
}
// the length of the number a will be stored in variable i
// the while loop below will store the digit from the end of str to the
// the beginning
while(i>0)
{
str[i]=a%10;
a=a/10;
i--;
}
// only for test
printf("the value of str is \"%llu\"\n", str[0]); //[0]
return 0;
}
最佳答案
while(i>0)
{
str[i]=a%10;
a=a/10;
i--;
}
这个循环不是一直计数到0,而是一直计数到1。如果
i
从不为0,则从不设置str[i]
。我怀疑是你写了
while(i>=0)
而编译器告诉你这行不通,因为i
永远不会是负数,因为它是无符号的。我就是这样的。奇怪的是迭代器是无符号的,也许是因为i
实际上是数字的个数,但是也没有真正的理由让它是无符号的。i
永远不应该大于20,它可能是一个short
。最小的修复方法是将
i
存储为有符号整数并切换到while(i>=0)
。我会进一步建议:
在
num_digits
中存储位数。只使用迭代器来避免混淆。
i
通常用作循环迭代器,将其用于任何其他用途或将其值持久化到下一个循环中是一个坏习惯。如果你必须这么做,那就换个名字吧。这也意味着在填充
i
的过程中,位数被破坏,无法打印所有str
。因此,将其单独存储在str
中,并根据需要将其复制到num_digits
中。使用
i
循环。对于简单的迭代,For循环非常清楚它是如何初始化的,如何递增的,以及结束条件是什么。你的第一个循环不适合for循环,但是你的第二个循环是。
根据需要声明变量。
这样可以避免忘记类型、它们初始化为什么以及所有的用途。它还使我们更容易看到应该将什么拆分成一个函数。
将
for
更改为str
。不是绳子。
将
digits
的类型更改为digits
。short
是单个数字的数组,没有一个大于9。为每一个分配64位是过分的。digits
可能溢出unsigned long long int
。这是代码中的另一个实际错误。
str[20]
保证至少是64位,但可能更多。如果是,则会溢出unsigned long long int
,该值固定为20。您必须根据str
来malloc
内存,或者使用str
中的num_digits
来显式获取无符号64位整数。把这一切放在一起。。。
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
// a will hold the number
uint64_t a=548763;
我们用的是
uint64_t
而不是stdint.h
inguint64_t
。YMMV,只要malloc
不能溢出。我选择了一个固定的大小以避免引入内存分配,您可能还没有了解到这一点。我没有签字就不用处理这个标志。// first we need to see the length of the number a
int num_digits = 0;
uint64_t b = a;
while( b>=10 ) {
b=b/10;
num_digits++;
}
我把它留作
str
循环,因为它不是一个简单的迭代器。根据需要声明变量(这将是一个很好的小函数)。它把数字存储在一个简单的整数中。short digits[20]= {0};
for( int i = num_digits; i >= 0; i-- ) {
digits[i]=a%10;
a=a/10;
}
这已经被重新处理成一个
str
循环,以表明这是一个简单的迭代器。while
已复制到num_digits
以便我们以后可以使用for
。它降到0。num_digits
现在是一个由1字节整数组成的数组;这就是存储从0到9的数字列表所需的全部内容。注意,
i
的初始值设定项是非标准的。应该num_digits
将所有元素初始化为0。for( int i = 0; i <= num_digits; i++ ) {
printf("the value of str is \"%d\"\n", digits[i]);
}
结果是我们仍然有
digits
来遍历short
。这可能是个练习。在产品代码中,您可以使用
{}
完成基本相同的任务。这也将处理负数,不需要无符号。int64_t a=548763;
char str[22] = {0}; // 1 extra for the possible sign, 1 for the null byte.
sprintf(str, "%"PRId64, a);
for( int i = 0; str[i] != '\0'; i++ ) {
printf("the value of str is \"%c\"\n", str[i]);
}
注意the types from stdint.h have their own printf format specifiers。
{0}
是64位数字的PRIntf格式。它是一个宏,必须在引号之外才能展开成自己的字符串。它利用了相邻的C字符串在编译时自动连接的优势。printf("This " "is all " "one string!\n");
关于c - long long数组在c中调用索引0时未返回期望值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505899/