罗蜜斯丹 2016-03-26 11:44 采纳率: 0%
浏览 1812
已采纳

C++初学问题!求教!为什么凡是数据中含有0就会出现问题?

// 输入10个整数,将这10个整数按升序排列输出,并且奇数在前‘偶数在后
//为什么凡是数据中含有0就会出现问题?
#include
using namespace std;

int main()
{
int N;
cout<<"请输入数字的总个数"< cin>>N;
int *a=new int[N];//动态创建一维数组
cout<<"现在请你逐一输入数据"< for(int i=0;i {
cin>>a[i];
if(i==N-1)
{
cout<<"以下就是处理后的数组"<<endl;
}
}
//判断奇偶,按奇数偶数来分成两个数组
int n=0,m =0;
int *odd=new int [n];//动态创建一维数组
int *even=new int [m ];//动态创建一维数组
for(int j=0;j<N;j++)
{
if(a[j]% 2==0)//判断,如果是偶数,则分到even数组里
{
even[m ++]=a[j];
}
else
{
odd[n++]=a[j];//其余则分到odd数组里
}
}

void sort(int *p,int n);//sort函数头文件 
sort(even,m );//调用sort函数来排序 
sort(odd,n);

for(int k=0;k<n;k++)
{
    cout<<odd[k]<<" ";
}
for(int l=0;l<m;l++)
{
    cout<<even[l]<<" ";
}
 delete []a;
 delete []odd;
 delete []even;
 return 0;

}

void sort(int p,int n)//传入数组首地址以及数组的大小
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(
(p+i)>(p+j))
{
int temp=
(p+j);
(p+j)=(p+i);
(p+i)=(p+j);
}
}
}
}

  • 写回答

1条回答

  • threenewbee 2016-03-26 14:07
    关注
     // app1.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    
    #include <iostream>
    using namespace std;
    
    void sort(int *p,int n);//sort函数头文件 
    
    int main()
    {
        int N;
        cout<<"请输入数字的总个数"<<endl; 
        cin>>N;
        int *a=new int[N];//动态创建一维数组 
        cout<<"现在请你逐一输入数据"<<endl; 
        for(int i=0;i<N;i++)
        {
            cin>>a[i];
        }
        cout<<"以下就是处理后的数组"<<endl;
    
        sort(a,N);//调用sort函数来排序 
    
        for(int l=0;l<N;l++)
        {
            cout<<a[l]<<" ";
        }
        delete [] a;
    
        return 0;
    }
    
    int compare(int x, int y)
    {
        if (x % 2 != y % 2) return x % 2 - y % 2;
        return y - x;
    }
    
    void sort(int *p,int n)//传入数组首地址以及数组的大小 
    {
        for(int i=n;i>1;i--)
        {
            for(int j=1;j<i;j++)
            {
                if(compare(*(p+j), *(p+j-1)) > 0)
                {
                    int temp=*(p+j);
                    *(p+j)=*(p+j-1);
                    *(p+j-1)=temp;
                }
            }
         } 
    }
    

    请输入数字的总个数
    8
    现在请你逐一输入数据
    3 1 0 4 2 7 11 8
    以下就是处理后的数组
    1 3 7 11 0 2 4 8 Press any key to continue

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题