生成10位有符号整数

时间:2013-10-25 12:10:01

标签: c linux random

这一行printf ("Random[%d]= %u\n", i, rand ());生成一个大概为1位的随机整数,但是当执行printf ("Random[%d]= %u\n", i, rand ()%1000000);时,它会生成6位int,

当尝试生成一个10位数的int时,错误“warning:format'%u'需要类型为'unsigned int'的参数,但参数3的类型为'long long int'[-Wformat]”。

有没有办法生成一个随机的10位有符号整数???

2 个答案:

答案 0 :(得分:2)

你会明确地或隐含地向printf传递sa“long long”或“unsigned long long”,这就是你得到警告的原因 - 但稍后会有更多内容;

生成一个10位数的随机数,你需要切换到64位 - 这么久;

unsigned long long randomvalue;
randomvalue = random();
randomvalue <<= 16; // just picked 16 at random
randomvalue ^= random();  // you could also use + but not "or";
randomvalue %= 10000000000ULL;

您收到的警告是因为您将long long类型的值作为第三个参数传递给printf函数,但仍然使用"%u"作为格式,这使得{{ 1}}期望值printf的值。

要使警告静音,请将格式更改为unsigned int

尽管如此,"%lld"会返回一个2147483647到目前为止最多32位,即使是64位,也无法帮助您创建高于rand的十位数字。位平台。价值int来自哪里?如果是带符号的32位整数,则为最高正值。

答案 1 :(得分:1)

它不适合int32(检查您的平台以了解int的定义方式)

在unsigned int32中,máximum值为2 ^ 32 = 4,294,967,296。因此,当您执行rand % 10000000000时,10000000000long,因此%计算为long操作(提供此类型的结果)