1 从键盘中任意输入5个整型数据存到数组a中,编程求出a中相邻两元素之和,并将这些和存到数组b中,按每行三个元素的形式输出。
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
int a[5],b[5],i;
printf("please input array a:\n");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=1;i<5;i++)
b[i]=a[i]+a[i-1];
for(i=1;i<5;i++)
{printf("%5d",b[i]);
if(i>=3)
printf("\n");
}
}
结果
2 选票系统
有三个候选人,输入参加选举的人数及每个人选举的内容,输出三个候选人最终得票数以及无效的选票数。
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
int v0=0,v1=0,v2=0,v3=0,i,n,a[50];
printf("please input the number of electorate:\n");
scanf("%d",&n);
printf("please input 1or2or3\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==1)
v1++;
else if(a[i]==2)
v2++;
else if(a[i]==3)
v3++;
else
v0++;
}
printf("the result:\n");
printf("candidate1:%d\ncandidate2:%d\ncandidate3:%d\nonuser:%d\n",v1,v2,v3,v0);
}
6.4.3 字符串的加密和解密
实现字符串的加密与解密
·加密方式:将字符串中每个字符加上它在字符串中的位置和一个偏移量3
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#define key 3 //偏移量
//函数声明
char * encrypt(char []);
char * dencrypt(char []);
int main()
{
char password[50]="1234569";
encrypt(password);
printf("加密后字符串为:%s\n",password);
dencrypt(password);
printf("解密后字符串为:%s\n",password);
return 0;
}
//函数定义
char * encrypt(char password[])
{
int i=0;
int count=strlen(password);
for(;i<count;i++)
{
password[i]=password[i]+i+key;
}
return password;
}
char * dencrypt(char password[])
{
int i=0;
int count=strlen(password);
for(;i<count;i++)
{
password[i]=password[i]-i-key;
}
return password;
}