代码改变世界

一些编程的小练手

2012-04-22 14:31  sensensen  阅读(149)  评论(0编辑  收藏  举报

第一个问题,电报加密问题,代码如下:

View Code
 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 
 6 int _tmain(int argc, _TCHAR* argv[])
 7 {
 8     while(true)
 9     {
10     string input;
11     getline(cin,input);//string里面有getline
12     const char *p=input.c_str();
13     char *q=new char;
14     char *q_begin=q;
15     while(*p!='\0')
16     {
17         int temp;
18         if(*p>='a'&&*p<='z')
19         {
20              temp=*p-'a'+1;
21         }
22         else if(*p>='A'&&*p<='Z')
23         {
24                temp=*p-'A'+27;
25         }
26         else
27         {
28             return 1;
29         }
30         temp=(temp*temp+temp+1)%52;
31 
32         if(temp>=27)
33         {
34             *q='A'+temp-27;
35         }
36         else
37         {
38             *q='a'+temp-1;
39         }
40         p++;
41         q++;
42     }
43     *q='\0';
44     string output=q_begin;
45     printf(q_begin,"%s");
46     printf("\n");
47     /*return 0;*/
48     }
49     return 0;
50 }

弄懂了关于iostream和using namespace std的一点问题,注意iostream等都需要using namespace std才能正确使用cout等函数。

这里对于控制台程序的输入,是通过string的一个函数getline来做的,它很好的一点就是有'\0',const char *p=input.c_str();这个函数也是带'\0'的。另外一点就是注意字母的ASCII值和真实的int值。

第二个问题,夫妻相,代码如下:

View Code
#include "stdafx.h"
#include "string.h"
#define MAX_GIRL_NUM 10
#define MAX_NAME_LEN 20
int main()
{
char asGirl[MAX_GIRL_NUM][MAX_NAME_LEN] = 
{"wang fei","zhang man yu","zhang zhi yi","li li","li xiao man",
"li yu cun","yang ni","xiao tong","li lei","zhang san"};

char sInputName[MAX_NAME_LEN];

gets(sInputName);
if (strlen(sInputName) >= MAX_NAME_LEN)
{
printf("Err:Out of range!");
return 0;
}
// 添加自己的业务代码
//分析输入的名字,得到其字母
bool alpha[26]={0};
for(int i=0;i<strlen(sInputName);i++)
{
    if(sInputName[i]==' ') 
    {
        continue;
    }
    alpha[sInputName[i]-'a']=true;
}

int score[MAX_GIRL_NUM]={0};
int name,scorehigh=0;
for(int i=0;i<MAX_GIRL_NUM;i++)
{
    bool match[26]={0};
    if(strlen(asGirl[i])==0)
        break;
    int j=0;
    for(j=0;j<strlen(asGirl[i]);j++)
    {
        if(alpha[asGirl[i][j]-'a']==true)
        {
            match[asGirl[i][j]-'a']=true;
        }
    }
    for(int k=0;k<26;k++)
    {
        score[i]=score[i]+match[k];
    }
    if(score[i]>scorehigh)
    {
        name=i;
        scorehigh=score[i];
    }
}
printf("\n");
printf(asGirl[name],"%s");


return 0;
}

 

关键注意点在于它要求的规则2,重复按一次处理,所以我想到了因为字母都是小写,可以统计字母a-z26个。还有一点要注意,对于空格,不要忽略了,这个,而导致以后运行的一些错误就可以了。