在密码学中,恺撒密码,或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,Z变成C,a变成d,x变成a,以此类推。这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系。
现在规定偏移量大小为n(1≤n≤25),每个样例提供一个字母给你进行加密,你需要输出加密后得到的字母。
输入格式
输入偏移量n(正数)和要加密的字符(注意区分大小写),中间用空格隔开。
输出格式
输出凯撒加密后的字符。
样例输入1
3 a
样例输出1
d
样例输入2
5 C
样例输出2
H
样例输入3
1 Z
样例输出3
A
直接使用if来判断吧。
代码如下:
#include <stdio.h>
int main(void){
char ch,result;
int offset;
scanf("%d %c",&offset,&ch);
if(ch>='a'&&ch<='z'){ // 如果是小写字母
result = ch + offset; // 输入的字符加上偏移
if(result>'z'){ // 如果偏移后的ASCII码大于'z'
result = 'a'+result-'z'-1; // 则计算出距离'a'偏移量后,再加上'a'
}
}else if(ch>='A'&&ch<='Z'){ // 如果是大写字母
result = ch + offset; // 同上, 输入的字符加上偏移
if(result>'Z'){ // 如果偏移后的ASCII码大于'Z'
result = 'A'+result-'Z'-1; // 则计算出距离'A'偏移量后,再加上'A'
}
}
// 打印结果
printf("%c",result);
return 0;
}
#include<stdio.h>
int main()
{void hanoi(int n,char one,char two,char three);
int m;
printf("input the number of diskes: ");
scanf("%d",&m);
printf("The step to move %d diskes:\n",m);
hanoi(m,'A','B','C');
}
void hanoi(int n,char one,char two,char three)
{
void move(char x,char y);
if(n==1)
move(one,three);
else{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
运行结果如下:
通过查看参考资料和问题要求,可以使用C++实现凯撒加密算法如下:
#include <iostream>
#include <string>
using namespace std;
string caesarCipher(string str, int shift) {
string result = "";
for (int i = 0; i < str.length(); i++) {
if (isalpha(str[i])) {
if (isupper(str[i])) {
result += char(int(str[i] + shift - 65) % 26 + 65);
}
else {
result += char(int(str[i] + shift - 97) % 26 + 97);
}
}
else {
result += str[i];
}
}
return result;
}
int main() {
int shift;
char character;
cin >> shift >> character;
string encryptedChar = caesarCipher(string(1, character), shift);
cout << encryptedChar << endl;
return 0;
}
通过上述代码,我们首先定义了一个名为caesarCipher
的函数,该函数接收一个字符串和一个整数偏移量作为参数,然后对字符串进行凯撒加密,并返回加密后的字符串。
主程序中,我们首先从用户处输入一个整数偏移量和一个字符要加密的字符。然后,我们使用caesarCipher
函数来加密给定的字符,并将结果打印出来。
需要注意的是,我们在caesarCipher
函数中使用了凯撒加密的算法来处理大小写字母,同时对非字母字符不作处理。
希望以上代码对你有所帮助,如果有任何疑问,请随时提出。
#include<bits/stdc++.h>
using namespace std;
int main()
{
char temp;
int a;
cin>>a>>temp;
if(temp+a>122 )
{
temp -= 26;
}
if(temp+a<97 && temp+a>90)
{
temp -= 26;
}
temp = temp + a;
cout<<temp;
}