gpt4 book ai didi

c - 在数组中设置随机数

转载 作者:行者123 更新时间:2023-11-30 18:24:38 25 4
gpt4 key购买 nike

我是一名初学者,刚刚开始学习,因此我将不胜感激任何信息和指导。

我想生成一个长度为 15 的数组,其中包含 0 到 10 之间的随机数。我想提示用户输入该范围内的数字,并打印出该数字出现的次数。然后我想打印出带有星号(*)的数组,指示该数组中该数字的每个实例

这是我正在处理的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
srand(time(NULL))
int r=rand(0)%10

int num; /*user's input*/
int r;
numbers[15]={r,r,r,r,r,r,r,r,r,r,r,r,r,r,r}
printf("Input a number between 0 and 10. \n")
for(num= ; num ; num++)
printf("*")

return 0;

}

最佳答案

I want to generate an array of length 15 containing random numbersbetween 0 and 10

  • 创建一个大小为 15 的数组
  • 使用 for 循环通过 rand() 函数填充数组。

Note :

  • use rand()%9+1 to return a random number between 0 and 10 (0,10 not included ) and don't send any arguments into rand() function.
int array[15]; //array of size 15

for(int index=0; index<15; index++)
{
array[index] = (rand()%9)+1; //randomly generates a number between 0 and 10
}
<小时/>

prompt the user for a number in that range and print out the number of times that number appears

  • 您想要实现的大部分目标都可以通过使用 for 循环来实现

在这里,我们扫描用户的数字并将其存储在 number 中,并循环遍历数组以查找 number 出现的次数,每次出现时我们都会增加该值count 的初始设置为 0

int number,count=0;
printf("enter a number between 0 and 10 : ");
scanf("%d",&number); //scanning user prompted number

for(int index=0; index<15; index++)
{
if(array[index]==number) //checking if array element is equal to user's input
count++; //if yes increase the count
}
printf("the number appeared %d times\n",count); //printing number of times the number appeared
<小时/>

I then want to print out the array with an asterisk(*) indicating each instance of that number in that array

for(int index=0; index<15; index++)
{
if(array[index]==number)
printf("* ");
else
printf("%d ",array[index]);
}
<小时/>

所以你的代码总共是:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
srand(time(NULL));

int array[15];

//populating array with random elements between 0 and 10
for(int index=0; index<15; index++)
{
array[index] = (rand()%9)+1;
}

int number,count=0;

//scanning user prompted input
printf("enter a number between 0 and 10 : ");
scanf("%d",&number);

//printing number of times the user entered number appeared
for(int index=0; index<15; index++)
{
if(array[index]==number)
count++;
}
printf("the number appeared %d times\n",count);

// printing the array with * in place of user entered input
for(int index=0; index<15; index++)
{
if(array[index]==number)
printf("* ");
else
printf("%d ",array[index]);
}

}

关于c - 在数组中设置随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com