#include<stdio.h>
#include<string.h>
//将输入的字符串a,将所有偶数项按下标从大到小放在a的后半部分,
//将所有奇数项按下标从小到大放在a的前半部分,输出a;
//如asdf变为adfs
//请问我的程序为什么不到达到要求?
main()
{
int i,j,n,m;
char a[10],b[10],d[10];
j=0;
gets(a);
n=strlen(a);
for(i=0;i<n;i=i+2){//奇数项
b[j]=a[i];
j++;
}
m=strlen(b);
puts(b);
j=0;
for(i=1;i<n;i=i+2){//偶数项
d[j++]=a[i];
}
m=strlen(d);
for(i=m-1;i>=0;i--)
putchar(d[i]);
}
----------------解决方案--------------------------------------------------------
你在哪里排序了?
----------------解决方案--------------------------------------------------------
/*---------------------------------------------------------------------------
File name: 比较费解的排序问题.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 8/22/2007 13:22:19
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
//将输入的字符串a,将所有偶数项按下标从大到小放在a的后半部分,
//将所有奇数项按下标从小到大放在a的前半部分,输出a;
//如asdf变为adfs
//请问我的程序为什么不到达到要求?
If you are allowed to use O(n) space, then this problem
is trivial; if you are only allowed to use O(1) space,
then the problem is challenging.
The code below assumes that you want to use O(n) space.
1234567890
Original string: 1234567890
Transformed string: 1357924680
Press any key to continue . . .
1234 6789
Original string: 1234 6789
Transformed string: 13 792468
Press any key to continue . . .
*/
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main(int argc, char** argv)
{
char a[N];
char aux[N];
int n;
int i;
int j=0;
scanf("%[^\n]", a);
printf("Original string: %s\n", a);
n=strlen(a);
for(i=0; i<n; i+=2)
{
aux[j]=a[i];
++j;
}
for(i=1; i<n; i+=2)
{
aux[j]=a[i];
++j;
}
for(i=0; i<n; ++i)
a[i] = aux[i];
printf("Transformed string: %s\n", a);
return 0;
}
----------------解决方案--------------------------------------------------------
#include<stdio.h>
#include<string.h>
main()
{
int i,j,n,m;
char a[10],b[10],d[10];
j=0;
gets(a);
n=strlen(a);
for(i=0;i<n;i=i+2){
b[j]=a[i];
j++;
}
b[j]='\0';//加上
m=strlen(b);
puts(b);
j=0;
for(i=1;i<n;i=i+2){
d[j++]=a[i];
}
d[j]='\0';//加上
m=strlen(d);
for(i=m-1;i>=0;i--)
putchar(d[i]);
}
//Ok了!我的错误在于没理解字符串以'\0'结尾。谢谢~~
----------------解决方案--------------------------------------------------------
版主的很好!
----------------解决方案--------------------------------------------------------