2017-05-27 34 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 

看东西了,让我知道,如果您有任何进一步的问题。

相关问题