【问题标题】:Simple C Program Error..Can't resolve it简单的 C 程序错误..无法解决
【发布时间】:2015-01-04 04:49:17
【问题描述】:

我正在尝试使用 srand() 在 C 中生成随机数。我想生成从 1 到 25 的数字而不重复,所以我实现了以下程序。

#include <stdio.h> 
#include <time.h>
int main()
{
int i=0,n,a[25]={0},b[25]={0},cntr=0;
srand(time(NULL));
while(cntr!=25)
{
    n=rand()%26;
    if(n!=9)
    {
        if(a[n]!=1)
        {
            a[n]=1;
            printf("%d  ",n);
            b[i]=n;
            printf("%d\n",b[i]);
            cntr++;
            i++;
        }
    }
}
for(i=0;i<25;i++)
{
    printf("%d  ",b[i]);
}
return 0;
}

现在有一个奇怪的问题。当我在生成随机数的循环内打印数组 b 时,它会打印正确的数字。但是当我在循环外打印它时,数组 b 的第一个元素变为 1,我在随机数中得到重复值 1。如果有人能帮助找出程序中的错误,我将不胜感激。

这是我提供程序输出的 ideone 的链接:Ideone Link

【问题讨论】:

  • 一个提示 - 以有意义的方式命名你的变量,愚蠢错误的原因就很清楚了。
  • @TymoteuszPaul 我已经检查了很多次但找不到。这就是我寻求帮助的原因
  • 我给了你一个非常简单的方法来找到它——重命名你的变量,让它们有意义。因此,当我查看 a[n]=1; 时,很清楚该数组的名称是什么,索引是什么,内容是什么。
  • 您似乎正在尝试生成 [0,25] 中除 9 之外的整数的随机排列。有比这更有效的方法来生成随机排列。
  • @harsh-jani 您可以从搜索“随机排列算法”开始。 Fisher-Yates Shuffle 是一种方法。基本上,与其生成数字并丢弃任何重复项,直到您拥有所需的所有数字,不如生成一个包含所有您想要的数字的数组,然后将每个位置与随机位置交换。

标签: c srand


【解决方案1】:

您声明了 a[25],但您访问了自 n=rand()%26; 以来的 26 个元素中的任何一个,因此请改为声明

 int i=0,n,a[26]={0},b[26]={0},cntr=0;

顺便说一句,编译时包含所有警告和调试信息(例如gcc -Wall -Wextra -g)。然后使用调试器 (gdb)。 watchpoint 会有所帮助。

【讨论】:

  • 这真是一个愚蠢的错误。我已经纠正了。感谢您的帮助:)
【解决方案2】:
there are several little oops in the posted code.
the following corrects those oops

#include <stdio.h>
#include <stdlib.h> // srand(), rand()
#include <time.h>   // time()

int main()
{
    int i=0; // generated number counter
    int n;  // generated number
    int a[25]={0}; // tracks which numbers have been generated
    int b[25]={0}; // random array of numbers 1...25

    srand(time(NULL));

    while(i<25)  // correct loop termination
    {
        n=rand()%25+1; // yields 0...24 +1 gives 1...25

        if(a[n]!=1)
        { // then, number not previously generated
            a[n]=1;   // indicate number generated

            printf("%d  ",n); // echo number

            // save number in current location in array 'b'
            b[i]=n;
            printf("%d\n",b[i]);  // echo number again

            i++; // step offset into array 'b' (and loop counter)
        } // end if
    } // end while

    for(i=0;i<25;i++)
    {
        printf("%d  ",b[i]);
    } // end for

    return 0;
}  // end function: main

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2022-01-10
    • 2012-04-18
    • 2013-11-13
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多