2013-11-27 1 views
0

컴퓨터 과학 프로젝트. 사용자가 배열의 크기를 선언 한 다음 배열을 숫자로 배열을 채우고 비어 있지 않은 순서로 채운 다음 값 x를 선언하는 프로그램을 만들어야합니다. 그런 다음 X가 적절한 지점에 지정되므로 전체 배열은 숫자가 줄어들지 않고 순서가 바뀝니다. 배열이 출력됩니다.C 프로그램 도움말 : 예기치 않은 출력

코드는 오류없이 올바르게 빌드되지만 출력이 엉망입니다.

#include <stdio.h> 

int main (void) { 

//Local Declarations 
int size; 
int ary[100]; 
int x; 
int i; 
int j; 

//Statements 
printf("Enter the size of the array: "); 
scanf("%d", &size); 

printf("\nEnter digits to fill the array, in numerical order: "); 
for (i = 0; i < size; i++) { 
    scanf("%d", &ary[i]); 
} 
size++; 

printf("\nInput x, the value to add to the array: "); 
scanf("%d", &x); 

while(i=0 <= x && x > ary[i]){ 
i++; 
j = size - 1; 
    while(j >= i) { 
     ary[j++] = ary[j]; 
     j--; 
    } 
} 
for(i = 0; i < size; i++) { 
printf("%d,", ary[i]); 
} 

return 0; 
} //main 

예 출력 :

Enter the size of the array: 5 

Enter digits to fill the array, in numerical order: 1 
2 
3 
4 
5 

Input x, the value to add to the array: 6 
1,2,3,4,5,1630076519, 
Process returned 0 (0x0) execution time : 8.585 s 
Press any key to continue. 

그것은 그 거대한 숫자로 엉망 마지막 값은 항상입니다. 나는 왜 내 인생에 대해 생각할 수 없다. 이 프로젝트는 EST 자정까지 예정되어 있습니다.

+2

의도가 여기에'I = 0 <= x' 무엇입니까? 논리 오류처럼 보입니다. –

+0

'ary [j ++] = ary [j];'도 논리적이 아니며 라인은 동일한 값을 자신에게 할당합니다. – rae1

+0

나는 i를 0으로 되돌려 줄 필요가 있지만, "i = 0;"의 while 루프 위에 문장을 만들면 프로그램이 충돌합니다. –

답변

0

while 루프를 들어,

i = 0; 
while (i < x && x > ary[i]) { 
    i++; 
    j = size - 1; 
    while (j >= i) { 
     j++; 
     ary[j] = ary[j]; // Equivalent to ary[j++] = ary[j];, yet easier to read 
     j--; 
    } 
} 
+0

이유는 확실하지 않지만 언제든지이 while 루프 전에 i의 값을 0으로 되돌려주는 명령문을 추가하면 프로그램이 멈 춥니 다. –

+0

아마'x> ary [i]'부분 일 것입니다. 배정 된 과제는 정확히 무엇입니까? – rae1

0

이 시도하는 대신이 시도 할 수 있습니다 :

#include <stdio.h> 

int main (void) { 

//Local Declarations 
int size; 
int ary[100]; 
int x; 
int i; 
int j; 
int temp1,temp2; 

//Statements 
printf("Enter the size of the array: "); 
scanf("%d", &size); 

printf("\nEnter digits to fill the array, in numerical order: "); 
for (i = 0; i < size; i++) { 
scanf("%d", &ary[i]); 
} 


printf("\nInput x, the value to add to the array: "); 
scanf("%d", &x); 

for(i=0;i<size;i++) 
{ 
    if(ary[i]>x) 
    { 
     temp1 = ary[i]; 
     ary[i] = x; 
     break; 
    } 
} 
if(i==size) 
{ 
    ary[i]= x; 
} 
else 
{ 

    for(j=i+1;j<size+1;j++) 
    { 
     if(j==size) //Last element of the new array 
     { 
      ary[j] = temp1; 
      break; 
     } 

     temp2 = ary[j]; 
     ary[j] =temp1; 
     temp1 = temp2; 


    } 
} 

for(i = 0; i < size+1; i++) { 
printf("%d,", ary[i]); 
} 

return 0; 
} //main