例如:輸入:420 50 -4 輸出:數字 3 正 2 負 1
同樣的代碼:輸入:420 50 -4 7 輸出:數字 4 正 3 負 1 在此處輸入影像描述
#include<stdio.h>
#define N 2
int main()
{
int a[N], i=0, n=0, k=0, z=0;
for(i=0; i<N; i )
{
scanf("%d" , &a[i]);
if((a[i] >= -10000 && a[i] <= 10000 ))
n ;
if(a[i]>0)
k ;
if(a[i]<0)
z ;
}
printf("Numbers:%d \n", n);
printf("Positive:%d \n", k);
printf("Negative:%d \n", z);
return 0;
}
uj5u.com熱心網友回復:
有幾種方法可以解決這個問題:
宣告一個足夠大的陣列,以容納可能的最大資料大小。
在資料的開頭包含一個大小,并使用它來分配陣列。
使用不依賴于固定大小的資料結構,例如鏈表。
uj5u.com熱心網友回復:
答案的幾個部分。
要么宣告一個不錯的大陣列,比您需要的大,要么提示用戶輸入大小,然后使用用戶輸入的大小來宣告或分配陣列。(這是一種流行的策略,但這是一種糟糕的用戶體驗,因為用戶不需要知道或說出他們將要輸入的數字。)
檢查 的回傳值
scanf。如果回傳值不是 1,則表示scanf失敗,并且沒有輸入數字。您可以將此視為用戶停止輸入數字的指示。有兩個變數:陣列的大小和實際輸入的數字數量。您可以通過在
scanf失敗時通知來設定實際輸入的數字數量。然后,稍后,當您處理陣列中的日期時,您不執行for(i = 0; i < N; i ),而是執行for(i = 0; i < number_of_numbers; i )。如果您不想要求用戶明確輸入數字的數量,并且您不想提前選擇一個“足夠大”的大小(要么是因為您不想浪費記憶體,要么是因為您想為了確保用戶可以輸入很多inout,可能比您選擇的任何數字都多),可以隨著用戶輸入越來越多的資料動態重新分配越來越大的陣列,但這是一個高級主題。
uj5u.com熱心網友回復:
此示例允許用戶“無限期”輸入數字,而無需提示輸入多少。當然,你的電腦只有這么多記憶體,所以有一個限制,但沒有實際限制。本質上,您需要選擇一個初始大小,然后在達到該大小時動態分配更多空間。
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10
void printArray(const int* myArray, size_t numsEntered)
{
for (size_t i=0; i<numsEntered; i )
{
printf("myArray[%zu] = %d\n", i, myArray[i]);
}
}
int main(void)
{
size_t arraySize = INITIAL_SIZE;
size_t numsEnteredSoFar = 0;
int* myArray = malloc(sizeof(*myArray) * arraySize); // initially make room for 10
if (myArray == NULL) exit(-1); // whoops, malloc failed, handle this error how you want
while(1)
{
int curEntry;
printf("enter a number, or 'q' to quit: ");
if (scanf("%d", &curEntry) == 1)
{
// store in the array, increment number of entries
myArray[numsEnteredSoFar ] = curEntry;
// here you can check for positives and negatives, or
// wait to do that at the end. The point of this example
// is to show how to dynamically increase memory allocation
// during runtime.
if (numsEnteredSoFar == arraySize)
{
puts("Array limit reached, reallocing");
// we've reached our limit, need to allocate more memory to continue.
// The expansion strategy is up to you, I'll just continue to add
// INITIAL_SIZE
arraySize = INITIAL_SIZE;
int* temp = realloc(myArray, arraySize * sizeof(*myArray));
if (temp == NULL)
{
// uh oh, out of memory, handle this error as you want. I'll just
// print an error and bomb out
fprintf(stderr, "out of memory\n");
exit(-1);
}
else
{
// realloc succeeded, we can now safely assign temp to our main array
myArray = temp;
}
}
}
else
{
// the user entered 'q' (or anything else that didn't match an int), we're done
break;
}
}
// print the array just to show it worked. Instead, here you can
// loop through and do your comparisons for positive and negative,
// or you can continue to track that after each entry as you've
// shown in your code
printArray(myArray, numsEnteredSoFar);
free(myArray);
return 0;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341514.html
標籤:C
