对数组中的负元素进行排序
Sort negative elements from an array
这是我在 C 中编写的代码的一部分。
我想要做的是检测一个数组中的负数并用这些负数填充另一个数组。同时,我想数那些负数。
所有这一切听起来都很简单,而且在我尝试打印负数元素之前一切似乎都很顺利。这就是我得到的:
6422204个数为负数
我根本不知道哪里出了问题,或者即使这是这样做的好方法。
代码如下:
double arr[10] = {21, -3.4, 65, 7.6, -12, 66, 10, -2, 5, 135};
int length = sizeof(arr)/sizeof(double);
printf("There are %d numbers in the array.\n",length);
for(int i = 0; i < 10; i++)
{
printf("[%d]=%.1lf ", i, arr[i]);
}
int neg = 0;
double negative[10];
for(int j = 0; j < 10; j++)
{
if(arr[j] < 0)
{
negative[j] = arr[j];
neg++;
}
}
printf("\n\n%d numbers are negative.", &neg);
感谢您的回答!
删除 printf
中的 &
:
printf("\n\n%d numbers are negative.", neg);
这是我在 C 中编写的代码的一部分。 我想要做的是检测一个数组中的负数并用这些负数填充另一个数组。同时,我想数那些负数。
所有这一切听起来都很简单,而且在我尝试打印负数元素之前一切似乎都很顺利。这就是我得到的: 6422204个数为负数
我根本不知道哪里出了问题,或者即使这是这样做的好方法。
代码如下:
double arr[10] = {21, -3.4, 65, 7.6, -12, 66, 10, -2, 5, 135};
int length = sizeof(arr)/sizeof(double);
printf("There are %d numbers in the array.\n",length);
for(int i = 0; i < 10; i++)
{
printf("[%d]=%.1lf ", i, arr[i]);
}
int neg = 0;
double negative[10];
for(int j = 0; j < 10; j++)
{
if(arr[j] < 0)
{
negative[j] = arr[j];
neg++;
}
}
printf("\n\n%d numbers are negative.", &neg);
感谢您的回答!
删除 printf
中的 &
:
printf("\n\n%d numbers are negative.", neg);