【问题标题】:Error in inputting random numbers in array在数组中输入随机数时出错
【发布时间】:2023-03-26 12:30:02
【问题描述】:

我尝试将随机生成的值保存在名为 population 的数组中,但是当我尝试显示数组中的值时,我发现它只保存每列的第一个数字的值,这不是我的意图。另外,如何更改此代码以保存随机双精度值?

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

// int *randNumsInRange(int upper, int lower, int count)
// {
//  //Declare index
//  int i;
//  //Decalre array in heap to save the randomly generated values
//  int* randNumsArray = (int*)malloc(sizeof(int) * count);
//
//  srand(time(0));
//
//  for (i = 0; i < count; i++)
//  {
//      randNumsArray[i] = (rand() % (upper - lower + 1)) + lower;
//  }
//
//  return randNumsArray;
// }

int main()
{
    //Declaration of variables

    //Variable 'numPoints' will hold the number of of points 
    //Variable 'order' will hold the order of the polynomial
    //Variable 'numPopulation' will hold the number of the population
    int numPoints, order, numPopulation;

    //Variable 'upper' and 'lower' will be used for limiting the coefficient values to certain boundaries
    int upper, lower;

    //Variable 'population' will hold the information of the population in 1D array converted from 2D array
    int* population;

    //Declare indexes for the loops
    int i, j, n;
    int row, col;

    //Variable 'iterCnt' will count the iterations, or so-called generations of the AI
    int iterCnt;

    //Initialize random number gerator by using the time of system clock in seconds
    srand(time(0));

    //Input order of the polynomial fit
    printf("Select the order of the polynomial fit.: ");
    scanf_s("%i", &order);
    printf("The fit will be drawn in the order of %u.\n\n", order);

    //Increment 1 from the value of order to include the constant
    int numCoefficient = order + 1;

    //Input number of population
    printf("Select the desired number of population: ");
    scanf_s("%i", &numPopulation);
    if (numPopulation > 20)
    {
        printf("WARNING: population that is too large can result in slower compilation\n");
    }
    printf("The function will now generate the %u numbers of points.\n\n", numPopulation);

    //Input number of points
    printf("How many points will be provided?: ");
    scanf_s("%i", &numPoints);
    printf("The function will now generate the %u numbers of points.\n\n", numPoints);

    //Initiailize heap location for the coordinates
    int* xData = (int*)malloc(sizeof(int) * numPoints);
    int* yData = (int*)malloc(sizeof(int) * numPoints);
    //can be replaced with the line below for stack:
    //int xData[100000];

    //Initialize heap location for the population which contains coefficient information in 2D array
    population = (int*)malloc(numPopulation * numCoefficient * sizeof(int));

    for (i = 0; i < numPoints; i++)
    {
        printf("Please enter the x coordinate of P(%i).\n", i + 1);
        scanf_s("%i", &xData[i]);
        printf("Please enter the y coordinate of P(%i).\n", i + 1);
        scanf_s("%i", &yData[i]);
    }

    //Get the estimated coefficient value boundary
    printf("What is the estimated absolute value of the coefficient?: ");
    scanf_s("%i", &upper);
    lower = -upper;
    printf("The coefficient will be initialized between %i and %i.\n\n", lower, upper);

    //Generate an initial population
    for (row = 0; row < numPopulation; row++)
    {
        for (col = 0; col < numCoefficient; col++);
        {
            n = (row * numCoefficient) + col;
            population[n] = (int)(rand() % (upper - lower + 1)) + lower; 
            printf("%i", population[n]);
        }

    }

    printf("\nCoefficient Array: \n\n");
    for (i = 0; i < (numPopulation * numCoefficient); i++)
    {
        printf("%i ", population[i]);
        printf("\n");
    }

    //Calculate fitness of the initial population

}

【问题讨论】:

  • 您能否通过以下方式澄清您的问题:(a) 将代码缩减为仅相关部分(即仅出现问题的部分,同时仍保持可编译性)和 (b) 显示输出是您得到的,以及您期望的输出(以及您期望的原因)。
  • 此外,请只问一个问题。最好为如何保存随机双精度值创建一个单独的问题。但首先检查其他问题是否尚未回答,例如。 :generate random double numbers in c++(请注意,虽然问题是针对 C++ 的,但公认的答案同样适用于 C)。
  • 除了预期和实际输出之外,还显示与输出对应的示例输入。

标签: c arrays


【解决方案1】:

for循环的末尾有一个分号,将数据写入填充缓冲区,如下所示:

for (col = 0; col < numCoefficient; col++);

这个分号会截断 for 循环语句,并且用大括号括起来的主体不是 for 循环的一部分,因此只执行一次。这就是为什么您在人口缓冲区内只能获得一个有效值的原因。您可以通过删除分号来解决此问题,如下所示。

for (col = 0; col < numCoefficient; col++)
{
    n = (row * numCoefficient) + col;
    population[n] = (int)(rand() % (upper - lower + 1)) + lower; 
    printf("%i", population[n]);
}

要生成随机双精度值,请点击查询中的其中一个 cmets 中提到的链接。

【讨论】:

  • 天哪。我怎么错过了?太感谢了。顺便问一下,如果我想在数组中添加十进制值该怎么办?必须更改代码的哪一部分才能这样做?
  • 您需要将人口变量的类型更改为double *。另外,我假设upperlower 变量指的是系数的最小值和最大值,因此它们也需要为double。您需要使用%lf 作为scanf 的格式说明符来输入double 值。请参阅此链接以查看您的代码已修改为使用十进制值:wandbox.org/permlink/lLmjebQV4LB8iCib 最后,不要忘记在不再需要分配的内存时释放它。
猜你喜欢
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多