gpt4 book ai didi

c - 如何生成新的随机数并转置矩阵?

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:48 25 4
gpt4 key购买 nike

感谢之前所有帮助过我的人。但是我对这个程序还有一些疑问。如何在新随机数等于先前随机数的情况下生成新随机数?还有如何转置矩阵?

#include "stdafx.h" 
#include "stdlib.h"
#include "time.h"


int _tmain(int argc, _TCHAR* argv[])
{
int num2 = 0;
int num=0, i, j;
int mtx[9][9] = {0};

while (num < 3 || num > 9) {
printf("Enter an integer (3-9): ");
scanf("%d", &num);
}
do
{
srand(time(NULL));

switch (num)
{
case 3: num2 = rand() % 8;
break;
case 4: num2 = rand() % 15;
break;
case 5: num2 = rand() % 24;
break;
case 6: num2 = rand() % 35;
break;
case 7: num2 = rand() % 48;
break;
case 8: num2 = rand() % 63;
break;
case 9: num2 = rand() % 80;
break;
}


for (i=0; i < num; ++i)
for (j=0; j < num; ++j)
mtx[i][j] = num2;
}
while ( num2 == num2);



for (i=0; i < num; ++i) {
for (j=0; j < num; ++j)
printf("%i ", mtx[i][j]);
printf("\n");
}



return 0;
}

更新:

#include "stdafx.h"
#include "stdlib.h"
#include "time.h"


int _tmain(int argc, _TCHAR* argv[])
{
int prevNum2 = 0;
int num2 = 0;
int num = 0, i, j; // Added initializers and loop counters
int mtx[9][9] = {0}; // Reserve enough space for the worst-case scenario

while (num < 3 || num > 9) { // Added input validation loop
printf("Enter an integer (3-9): ");
scanf("%d", &num);
}

srand(time(NULL));

do{

prevNum2 =num2;
switch (num)
{
case 3: num2 = rand() % 8;
break;
case 4: num2 = rand() % 15;
break;
case 5: num2 = rand() % 24;
break;
case 6: num2 = rand() % 35;
break;
case 7: num2 = rand() % 48;
break;
case 8: num2 = rand() % 63;
break;
case 9: num2 = rand() % 80;
break;

}




// Loop through the matrix elements we want, filling each with a random number
for (i=0; i < num; ++i)
for (j=0; j < num; ++j)
mtx[i][j] = num2;
}
while (num2 == prevNum2);

/* Do something with the matrix here (display it, etc) */

for (i=0; i < num; ++i) {
for (j=0; j < num; ++j)
printf("%i ", mtx[i][j]);
printf("\n");
}



return 0;
}

最佳答案

读取的代码段

 switch (num)
{
case 3: num2 = rand() % 8; break;
case 4: num2 = rand() % 15; break;
case 5: num2 = rand() % 24; break;
case 6: num2 = rand() % 35; break;
case 7: num2 = rand() % 48; break;
case 8: num2 = rand() % 63; break;
case 9: num2 = rand() % 80; break;
}

可以重写为

 num2 = rand() % ((num * num) - 1);

哪个更紧凑,可以说更清晰。

关于c - 如何生成新的随机数并转置矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1922126/

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