g_random_int() returns 负数
g_random_int() returns negative numbers
这是来自 GLib 的 g_random_int() 函数的文档:
guint32 g_random_int (void);
Return a random guint32 equally distributed over the range [0..2^32-1].
但是下面的代码returns负数:
for (i=0; i< 10; ++i)
printf("Random: %d\n", g_random_int());
我明显遗漏了一些东西。
问题出在您的 printf
格式字符串中。
%d
是有符号整数的 format-specifier。
您正在有效地读取无符号整数,就像它是有符号的一样。
改用%u
:) 然后你的代码变成
for (i=0; i< 10; ++i)
printf("Random: %u\n", g_random_int());
这是 C 中各种 format-specifier 的参考:http://www.cplusplus.com/reference/cstdio/printf/
编辑
我相信这是 C99 标准中描述格式化 output-functions 未定义行为情况的段落,@12431234123412341234123 指的是:
In a call to one of the formatted output functions, a precision appears with a conversion specifier other than those described (7.19.6.1, 7.24.2.1).
.. 或者可能是这样的:
An invalid conversion specification is found in the format for one of the formatted input/output functions, or the strftime or wcsftime function (7.19.6.1, 7.19.6.2, 7.23.3.5, 7.24.2.1, 7.24.2.2, 7.24.5.1).
有关未定义行为的更多案例,请参阅此页面:https://gist.github.com/Earnestly/7c903f481ff9d29a3dd1
EDIT2
请参阅评论部分以更明智地讨论该问题。
这是来自 GLib 的 g_random_int() 函数的文档:
guint32 g_random_int (void);
Return a random guint32 equally distributed over the range [0..2^32-1].
但是下面的代码returns负数:
for (i=0; i< 10; ++i)
printf("Random: %d\n", g_random_int());
我明显遗漏了一些东西。
问题出在您的 printf
格式字符串中。
%d
是有符号整数的 format-specifier。
您正在有效地读取无符号整数,就像它是有符号的一样。
改用%u
:) 然后你的代码变成
for (i=0; i< 10; ++i)
printf("Random: %u\n", g_random_int());
这是 C 中各种 format-specifier 的参考:http://www.cplusplus.com/reference/cstdio/printf/
编辑
我相信这是 C99 标准中描述格式化 output-functions 未定义行为情况的段落,@12431234123412341234123 指的是:
In a call to one of the formatted output functions, a precision appears with a conversion specifier other than those described (7.19.6.1, 7.24.2.1).
.. 或者可能是这样的:
An invalid conversion specification is found in the format for one of the formatted input/output functions, or the strftime or wcsftime function (7.19.6.1, 7.19.6.2, 7.23.3.5, 7.24.2.1, 7.24.2.2, 7.24.5.1).
有关未定义行为的更多案例,请参阅此页面:https://gist.github.com/Earnestly/7c903f481ff9d29a3dd1
EDIT2
请参阅评论部分以更明智地讨论该问题。