c - 在c中生成随机码
问题描述
我正在尝试生成一个随机的 10 位代码,但即使我使用代码中每个数字的绝对值,它有时仍会打印一个负值
#include <stdio.h>
int main()
{
int i;
int r;
int barcode[11];
srand(time(NULL));
for(i=0;i <= 10;i++){
r = rand() % 10;
barcode[i] = abs(r);
}
printf("%d",barcode);
return 0;
}
解决方案
因为您实际上是在打印整数数组的地址,而不是字符串。
这一行:
printf("%d",barcode);
基本上将地址打印barcode
为有符号整数而不是条形码的内容。
你当然可以这样做:
printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);
但也许更好的方法是生成字符串而不是整数数组。对您的代码进行快速修改是'0'
在循环的每次交互中添加到每个随机值并附加到 char 数组。
int main()
{
int i;
int r;
char barcode[11]; // array of chars instead of ints
srand(time(NULL));
for(i=0; i < 10; i++) // loop 10 times, not 11
{
r = rand() % 10;
barcode[i] = '0' + r; // convert the value of r to a printable char
}
barcode[10] = '\0'; // null terminate your string
printf("%s\n",barcode);
return 0;
}
以上将生成一个 10 位代码,第一个数字很可能是前导零。如果这不是您想要的,那是一个简单的错误修复。(我将留给你...)
推荐阅读
- javascript - 为什么这段代码不起作用?以及如何让它发挥作用?
- android - createAnimatedSwitchNavigator undefined 不是函数
- algorithm - 市场排名算法
- elasticsearch - 将数据节点添加到集群后,ElasticSearch 可以重新启动吗?
- sql - 父、子、子 CTE
- php - CSS样式未出现在PHP页面上
- composer-php - composer.json 中缺少 Ext-json
- php - 如何在我的代码中的 3 列之后创建新行
- laravel - 在 1 个视图中显示 2 个表格
- xamarin - Xamarin,当用户改变主意时,有没有办法更新选择器上的列表?