做题速度越来越快啦!
第二章 C/C++快速入门——2.5数组
【习题A】 有序插入
Problem Description
有一个已排好序的数组,要求输入一个数后,按原来排序的规律将它插入到数组中。
假设数组长度为10,数组中前9个数(这9个数要求从键盘上输入,输入时要满足自小到大的输入顺序)已经按从小到大进行排序。
然后再从键盘上输入一个整数,将此整数插入到前有序的9个数中,使得最终的10个数依然是从小到大有序的。
Input 第一行输入以空格分隔的9个整数数,要求按从小到大的顺序输入。
第二行输入一个整数
Output 从小到大输出这10个数,每个数一行。
Sample Input 1 11 21 31 41 51 61 71 81 45
Sample Output 1 11 21 31 41 45 51 61 71 81
Thinking Notes
-
一开始把n<a[i]的条件判断反了 -
移动的时候要从后端开始
Code Implementation(C)
#include<stdio.h>
int main(){
int n;
int a[10];
for(int i=0;i<9;i++){
scanf("%d",&a[i]);
}
scanf("%d",&n);
int k;
for(k=0;k<9;k++){
if(n<a[k]) break;
}
for(int i=8;i>=k;i--){
a[i+1]=a[i];
}
a[k]=n;
for(int i=0;i<10;i++){
printf("%d\n",a[i]);
}
return 0;
}
【习题B】 数组元素逆置
Problem Description
将一个长度为10的整型数组中的值按逆序重新存放。
如:原来的顺序为1,2,3,4,5,6,7,8,9,0,要求改为0,9,8,7,6,5,4,3,2,1
Input 从键盘上输入以空格分隔的10个整数。
Output 按相反的顺序输出这10个数,每个数占一行。
Sample Input 1 2 3 4 5 6 7 8 9 0
Sample Output 0 9 8 7 6 5 4 3 2 1
Code Implementation(C)
#include<stdio.h>
int main(){
int a[10];
for(int i=0;i<10;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<5;i++){
int t;
t=a[i];
a[i]=a[9-i];
a[9-i]=t;
}
for(int i=0;i<10;i++){
printf("%d\n",a[i]);
}
return 0;
}
【习题C】 杨辉三角
Problem Description
按要求输入如下格式的杨辉三角
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
最多输出10层
Input 输入只包含一个正整数n,表示将要输出的杨辉三角的层数。
Output 对应于该输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开
Sample Input 5
Sample Output 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Code Implementation(C)
#include<stdio.h>
#include<string.h>
int main(){
int a[10][10],n;
scanf("%d",&n);
memset(a,0,sizeof(a));
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
if(i==j || j==0){
a[i][j]=1;
}
else{
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
【习题D】 解密
Problem Description
有一行电文,已按如下规律译成密码:
A–>Z a–>z
B–>Y b–>y
C–>X c–>x
… …
即第一个字母变成第26个字母,第i个字母变成第(26-i+1)个字母,非字母字符不变。要求根据密码译回原文,并输出。
Input 输入一行密文
Output 解密后的原文,单独占一行。
Sample Input ZYX123zyx
Sample Output ABC123abc
Thinking Notes
-
注意(26-i+1)解密公式中的i是26个字母的序号,不要与字符串的下标j混淆 -
字母值和字母序号的转换: (26-i+1): i 是字母序号,由(a[j]-‘a’)+1转换成字母值; (26-i+1)是解密后的字母序号,由(26-i+1)+(‘a’-1)转换成字母值 将i替换,从而得到解密后的字母值(26-(a[j]-‘a’)+1+1)+(‘a’-1) -
注意字母序号和字母值转换时,加减‘a’要有1的差量
Code Implementation(C)
#include <stdio.h>
#include <string.h>
int main(){
char a[100];
scanf("%s",a);
for(int j=0;j<strlen(a);j++){
if(a[j]>='a'&&a[j]<='z'){
a[j]=26-((a[j]-'a')+1)+1+('a'-1);
}
else if(a[j]>='A'&&a[j]<='Z'){
a[j]=26-((a[j]-'A')+1)+1+('A'-1);
}
}
printf("%s\n",a);
return 0;
}
|