【问题标题】:Generating integers in the diagonal of an array through a condition通过条件在数组的对角线上生成整数
【发布时间】:2014-04-01 19:47:26
【问题描述】:

我必须不断生成 10 x 10 数组,直到数组的对角线包含大于或等于 7 的数字。但是尝试次数不应增加一百万。如果尝试次数少于一百万,即打印出对角线上的数字大于 7 的数组和尝试次数。这是我的代码,问题是我的代码总是显示尝试次数超过一百万。有人可以看看代码并告诉我为什么它不能正常工作吗?

int i, j, matrix2[10][10], attempts, count = 0; 
for (attempts=0; attempts<1000000; attempts++)
{
    for (i=0; i<10; i++)
    {
        for (j=0; j<10; j++)
        {
            matrix2[i][j] = rand()%10;
            if(i==j&&matrix2[i][j] >= 7)
                count++;
        }
    }
}
printf("\n\nNumber of attempts : %d", count);
if (attempts >= 1000000)
    printf("\n\nNumber of attempts exceed one million :\t ACTION TERMINATED!!!");
else
{
    for (i=0; i<10; i++)
    {
        for (j=0; j<10; j++)
            if (i==j&&matrix2[i][j] >= 7)
                printf("%5d",matrix2[i][j]);
    printf("\n\n");
    }
}

【问题讨论】:

    标签: c arrays multidimensional-array


    【解决方案1】:

    简单:) 第一个循环将在尝试达到 1000000 时结束:

    attempts = 999998; //continue
    attempts = 999999; //continue
    attempts = 1000000; //stop
    

    然后,您正在检查尝试次数是否大于或等于 1000000,并且它等于 :)

    你应该检查它是否更大:

    if (attempts > 1000000)
    

    问候, 卡穆

    【讨论】:

      【解决方案2】:

      在第一次尝试时进行。替换:

      matrix2[i][j] = rand()%10;
      if(i==j&&matrix2[i][j] >= 7)
          count++;
      

      与:

      matrix2[i][j] = i==j?rand()%3+7:rand()%10;
      

      并移除重试循环。

      如果你出于某种深不可测的原因想要继续生成和丢弃,请为你真正成功的情况添加一个中断条件!

      【讨论】:

      • 谢谢你,但是显示尝试次数怎么样?
      • 嗯,这只是一次尝试,它成功了。你可以直接输出。
      猜你喜欢
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多