2017-05-27 35 views
-2

我創建一個由用戶給出的數組,大小和值,然後只將正偶數值存儲到另一個數組中,但我只得到0作爲答案。只將正數偶數值從一個數組存儲到另一個數組中

# include <stdio.h> 
int main() 
{ 
    int n, i; 
    float num[10], A[10]; 

    printf("Enter the numbers of elements: "); 
    scanf("%d", &n); 

    for(i = 0; i < n; ++i) 
    { 
     printf("%d. Enter number: ", i+1); 
     scanf("%f", &num[i]); 
    } 
    for(i = 0; i < n; ++i) 
    { 
     if(num[i] > 0 && fmod(num[i],2)==0){ 
      A[i] = num[i]; 
     } 
    } 
    printf("Positive, even values of the new created array are%d\t", A[i]); 

    return 0; 
} 
+1

'用戶給出的大小和值......你爲什麼要_lying_? :) –

+0

'數組是%d' - >'數組是%f',並使用循環輸出 – BLUEPIXY

+6

價格問題:'我'有什麼值_after_ for循環完成後? – CBroe

回答

0

您必須初始化n。小心; n應該不大於10.

您正在打印的值只有一個值A[i]。我想你想循環。

for(i = 0; i < n; ++i) 
{ 
    if(num[i] > 0 && fmod(num[i],2)==0){ 
     A[i] = num[i]; 

    printf("Positive, even values of the new created array are %lf\n", A[i]); 
    } 

} 
+1

或者他打算在任何情況下只打印「i」(即複製到數組中的值的數量)而不打印「%d」格式說明符不正確的「A [i]」。 – Clifford

0

可以很簡單地通過檢查從所述第一陣列中的每個值大於或等於零填補只甚至號碼第二陣列,然後通過檢查是否位0 (1位)爲零,例如

for (int i = 0; i < MAX; i++) { 
     a[i] = rand() % LIM - 4999;   /* random -4999 - 5000 */ 
     if (a[i] >= 0 && !(a[i] & 1))  /* if pos and even */ 
      b[n++] = a[i];     /* store in b array */ 
    } 

(注:用於以上所述第一陣列的64個值是-4999 - 5000之間的隨機值,得到僅選擇正/偶數的一個很好的測試)

在此之後,可以打印兩個陣列是一種合理的格式,可以輕鬆確認操作。把所有的拼在一起,你可以這樣做以下:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

#define MAX 64 
#define LIM 10000 

int main (void) { 

    int a[MAX] = {0}, b[MAX] = {0}, n = 0; 
    srand (time (NULL)); 

    for (int i = 0; i < MAX; i++) { 
     a[i] = rand() % LIM - 4999;   /* random -4999 - 5000 */ 
     if (a[i] >= 0 && !(a[i] & 1))  /* if pos and even */ 
      b[n++] = a[i];     /* store in b array */ 
    } 

    printf ("original array:\n\n");   /* output original array */ 
    for (int i = 0; i < MAX; i++) { 
     if (i && (i % 8) == 0) 
      putchar ('\n'); 
     printf (" %5d", a[i]); 
    } 
    putchar ('\n'); 

    printf ("\npositive even array:\n\n"); /* output pos/even array */ 
    for (int i = 0; i < n; i++) { 
     if (i && (i % 8) == 0) 
      putchar ('\n'); 
     printf (" %5d", b[i]); 
    } 
    putchar ('\n'); 

    return 0; 
} 

示例使用/輸出

$ ./bin/arrayposeven 
original array: 

    -68 3112 1571 -1926 1263 -1424 554 3181 
    1701 -4545 -956 4442 -431 -2333 -4373 3972 
-3033 2539 -1926 794 4050 1318 3323 120 
-3253 4451 781 2979 519 -2224 4251 1802 
-4113 -2827 1227 -1499 -2899 -3220 3033 3801 
-2765 -2923 3242 1803 -3905 220 -2874 4413 
-2242 200 206 -3193 -3483 -1471 -1722 4615 
    4331 410 2593 -3799 3185 -1804 3002 424 

positive even array: 

    3112 554 4442 3972 794 4050 1318 120 
    1802 3242 220 200 206 410 3002 424 

看東西了,讓我知道,如果您有任何進一步的問題。

相關問題