[英]How do you load an array with up to 10,000 numbers in C with a for loop?
這是我到目前為止。 我的隨機數生成器可以工作,但我不確定如何將用戶想要的數字加載到數組中。 它還檢查以確保輸入的數字超過 2 個且少於 10,000 個。
#include <stdio.h>
int randu(int randoms);
int main (int argc, char *argv[]) {
int numsor;
int randoms[];
int x=0;
if (argc == 1){
printf("How many numbers do you wish to sort? \n");
scanf("%d", &numsor);
}
if (argc == 2){
sscanf(argv[1], "%d", &numsor);
}
if (argc > 2){
printf("how many numbers do you wish to sort? \n");
scanf("%d", &numsor);
}
while (numsor<2 || numsor>10000){
if (numsor < 2){
printf("Error please enter a number more than 2. \n");
}
else{
printf("Error please enter a number less than 10,000. \n");
}
scanf("%d", &numsor);
}
}
int randu(int numsor){
static int seed=17;
seed=(25179*seed+13849)%65536;
return seed;
};
這是我應該通過的確切偽代碼。
編寫一個程序,允許用戶生成任意數量的隨機數(最多 10,000 個),將它們按升序排序,然后打印排序后的數字。 您必須使用數組來存儲數字,並使用子例程來生成和排序數字。 您必須確保用戶選擇至少 2 個號碼但不超過 10,000 個。 用戶希望排序的數字數量可能來自命令行,如果不是,則應提示用戶。 排序的輸出必須在一行上,由一個空格分隔。
Main的偽代碼:
如果用戶在命令行輸入要生成和排序的數字數量
o 轉換該數字並將其分配給適當的變量 否則
o 詢問用戶他們希望生成和排序的數字數量
o 將輸入讀入適當的變量
當用戶輸入的數字數量小於 2 或大於 10,000
o 顯示錯誤信息
o 詢問他們希望生成和排序多少個數字 o 閱讀輸入
----這就是我的問題開始的地方。------
使用 for 循環將指定數量的隨機數加載到數組中
調用冒泡排序器(傳遞數組和其中的項目數)
使用 for 循環打印從第一項到最后一項的排序數組。
int randu(void);
Definitions:
int randu(){
static int seed= 17;
seed = (25179*seed+13849)%65536; return seed;
}
void bubble(int *, int);
void bubble(int a[], int n) { int i, j;
for (i = 0; i < n-1; i++) for (j = n-1; i < j; j--)
if (a[j-1] > a[j]) swap(&a[j-1],&a[j]);
void swap(int *, int *);
void swap(int *a, int *b) { int temp;
temp = *a; *a = *b; *b = temp;
}
}
只需這樣做: int* randoms = (int *)malloc(sizeof(int)*numsor); // 分配整數
只需使用 for(int i = 0; i < numsor; i++) { randoms[i] = 在這里生成隨機數; }
#include "stdio.h"
#include "malloc.h"
int randu() {
static int seed= 17;
seed = (25179*seed+13849)%65536;
return seed;
}
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void bubble(int a[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = n-1; i < j; j--) {
if (a[j-1] > a[j]) {
swap(&a[j-1],&a[j]);
}
}
}
}
void main (int argc, char *argv[]) {
int numsor;
/* Your input logic here ... */
int* randoms = (int*)malloc(sizeof(int) * numsor);
for (int i = 0; i < numsor; i++) {
randoms[i] = randu();
}
bubble(randoms, numsor);
for (int i = 0; i < numsor; i++) {
printf("[%d]: %d\n", i, randoms[i]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.