2013-11-27 57 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. 

它总是弄乱到数量巨大的最后一个值。我不能为了我的生活找出原因。该项目将在美国东部时间午夜前公布。

+2

什么是你的意图在这里'I = 0 <= x'?看起来像一个逻辑错误。 –

+0

'ary [j ++] = ary [j];'也是非逻辑的:该行为其自身分配相同的值。 – rae1

+0

我需要返回到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