【发布时间】:2015-04-04 17:54:35
【问题描述】:
所以我环顾四周,发现关于 %n 的一般信息很少,也没有关于如何将它与变量一起使用的信息。
据我所知,我使用的代码应该可以工作,但我不知道它不是什么。我遇到问题的特定行是:
printf("%d %n", num[x], &c);
下面是完整的代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//seed rand, declare arrays, declare variables
srand(time(NULL));
int num[10];
int c = 0;
int total = 0;
int x;
printf( "%s%14s%20s\n", "Value", "Characters", "Total Characters" );
//Loads the num array with random numbers.
for(x = 1; x < 10; x++)
{
num[x] = 1 + rand() % 1000;
}
for (x = 1; x < 10; x++)
{
printf("%d %n", num[x], &c);
printf("%14d", c);
total = total + c;
printf("%20d\n", total);
}
}
【问题讨论】:
-
顺便说一句:对 rand() 的输出进行 any 类型的计算将在统计上 减少 其随机性,您正在有效地生成伪随机数哪些是更多可预测的。
-
@specializt 当然,“对 rand() 输出的任何类型的计算都会降低其随机性”夸大了您原本有效的担忧。示例:
num[x] = rand() ^ 12345;不会这样做。 -
在输出上使用 XOR 会降低其随机性 - 您只是将可能的值缩小到一个较小的集合。这是初学者的常见错误,也是密码系统在某些时候被破坏的真正原因。如果您想要任何程度的随机性,您需要获得一个可以创建所需范围的来源。就这么简单。要么继续收集数据,直到某些东西在你的范围内——这也将减少随机性,但至少值到达的时间点是不可预测的,这至少是一些讨价还价