#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
char str[1000];
int num[1000];
gets(str);
int count=0;
for (int i = 0; i <strlen(str); i+=2)
{
for (int j = i+2; j <strlen(str); j+=2)
{
if(((str[i]-'0')%(str[j]-'0'))==0)
{
num[count]=str[i]-'0';
count++;
break;
}
}
}
sort(num,num+count);
for (int i = 0; i < count-1; i++)
{
cout<<num[i]<<" ";
}
cout<<num[count-1];
}
以上代码只是适合一位整数:
修改如下:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
char str[1000];
int num[1000];
int count=0;
cin.getline(str, 1000);
int len = strlen(str);
int num_i=0;
char tmp[20];
int tmp_i=0;
for (int i = 0; i < len; ++i)
{
tmp_i = 0;
if(str[i] != ',')
{
while(str[i] != ',' && str[i] != '\0')
{
tmp[tmp_i++] = str[i++];
}
tmp[tmp_i] = '\0';
num[num_i++] = atoi(tmp);
count++;
}
}
int res[1000];
int n=0;
for (int i = 0; i < count; ++i)
{
for (int j = 0; j < count; ++j)
{
if(0==(num[i]%num[j]) && i!=j)
{
res[n++]=num[i];
break;
}
}
}
sort(res,res+n-1);
for (int i = 0; i < n; i++)
{
cout<<res[i]<<" ";
}
cout<<endl;
return 0;
}