我需要編寫一個程序,在該程序中我必須掃描整數,它們必須在1到30之間,並且當第二次輸入某個數時,我必須printf它是什麼數字,輸入的位置是什麼。我怎樣才能找出什麼時候是一定數量的輸入? C
例如,如果scanf的號碼是1 3 5 7 3,程序必須printf「號碼3是第二個掃描號碼」。
誤會我的是如何找出輸入號碼的位置是什麼,如何找出3號碼是在第二位置輸入的。
我只能用stdio.h來編寫這個程序。
我需要編寫一個程序,在該程序中我必須掃描整數,它們必須在1到30之間,並且當第二次輸入某個數時,我必須printf它是什麼數字,輸入的位置是什麼。我怎樣才能找出什麼時候是一定數量的輸入? C
例如,如果scanf的號碼是1 3 5 7 3,程序必須printf「號碼3是第二個掃描號碼」。
誤會我的是如何找出輸入號碼的位置是什麼,如何找出3號碼是在第二位置輸入的。
我只能用stdio.h來編寫這個程序。
您可以保存在一個陣列中讀取的數字,如下面的代碼:
#include <stdio.h>
int main() {
int vet[10000]; // assuming you wont enter more than 10000 numbers
int i = 0;
while (1) {
scanf ("%d", &vet[i]);
for (int j = 0; j < i; j++) {
if (vet[i] == vet[j]) {
printf ("Number %d was %dth scanned number", vet[i], j+1);
break;
}
}
i++;
}
}
另一種方法(這是好多了,但只是可能的,因爲輸入的限制),是存儲在一個數組,其中數首次發現,和-1如果它沒有找到,像位置如下:
#include <stdio.h>
int main() {
int vet[31];
int aux, counter;
for (int i = 0; i <= 30; i++)
vet[i] = -1; //not found yet
counter = 1;
while (1) {
scanf ("%d", &aux);
if (aux < 1 || aux > 30) { //check for wrong input
continue;
}
if (vet[aux] == -1) {
vet[aux] = counter;
}
else {
printf ("Number %d was %dth scanned number", aux, vet[aux]);
}
counter++;
}
}
非常感謝您,您的第一個代碼儘管稍微修改了一下,但卻爲我工作。沒有嘗試第二個代碼,但會嘗試。 – leon000
通常,第一個代碼非常糟糕,因爲它在不需要時立即在堆棧上分配內存。第二種方法好得多。你應該避免的第一個解決方案 – ForeverStudent
當然了,但是還是不工作,如果輸入不限如果其浮動,例如。 –
你想保持的30位的數組跟蹤第一個索引,每一個的號碼已輸入。 請記住,數組開始索引0 這個程序,直到你按下ctrl + C
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello world!\n");
int indexOfFirstOccurrence[30];
int i;
for(i=0;i<30;++i)indexOfFirstOccurrence[i]=0;
int counter=1;
int input;
while(1)
{
printf("please enter input #%d: ",counter);
scanf("%d", &input);
//error checking would be advised
if(indexOfFirstOccurrence[input-1]==0)indexOfFirstOccurrence[input-1]=counter;
printf("the first time %d was entered was at iteration %d \n",input, indexOfFirstOccurrence[input-1]);
counter++;
}
return 0;
}
顯示你嘗試的程序將無限期地運行。 – Idos
我已經刪除了代碼,我會試着解釋我在做什麼,如果你想要,我可以重寫我之前做過的代碼。所以我創建了一個30個整數的數組,每個int表示一個介於1和30之間的數字,然後在for循環中掃描數字,並將for循環(1,2,3 ...)的計數器保存到數組位置然後在另一個for循環中檢查新掃描的號碼是否已被掃描,然後獲取保存在該特定陣列位置的號碼。但那並不奏效。如果需要,我可以使用代碼關閉並重新打開該問題 – leon000