这是我写的一个小小的加密器,我只是想让人们告诉我什么是好做法,什么不是。而且,我指的是代码,而不是实际的加密(因为这只是一件愚蠢的事情)。
#include "stdafx.h"
#include <iostream>
#include <stdexcept>
using namespace std;
int encrypter(int input);
int decrypter(int input);
bool whatToDoFunc();
int main()
{
try
{
bool keepGoing = true;
while (keepGoing)
{
bool success = whatToDoFunc(); char redo;
cout << "Press 'y' to redo or anykey to exit" << endl;
cin >> redo;
if (success == true && (redo == 'y' || redo == 'Y'))
keepGoing == true;
else
keepGoing = false;
}
}
catch (runtime_error err)
{
cout << err.what() << endl;
char exitCon;
cout << "Enter anykey to exit" << endl;
cin >> exitCon;
return -1;
}
return 0;
}
bool whatToDoFunc()
{
int input;
char whatToDo;
cout << "Welcome to the JeGo encrypter what do you want to do encrypt or decrypy? Enter E or D\n" << endl;
cin >> whatToDo;
if (whatToDo == 'e' || whatToDo == 'E')
{
cout << "Enter the number you want to encrypt" << endl;
cin >> input;
int inputEncrypted = encrypter(input);
cout << "Your number encrypted is " << inputEncrypted << endl;
}
else
{
if (whatToDo == 'd' || whatToDo == 'D')
{
cout << "Enter the already encrypted number" << endl;
cin >> input;
int numDecrypted = decrypter(input);
cout << "Your number decrypted is " << numDecrypted << endl;
}
else
{
cerr << "Error" << endl;
throw runtime_error("Your input was invalid");
}
}
return true;
}
int encrypter(int input)
{
int inputEncrypted;
inputEncrypted = ((((input * 2) + 7) + 5) + 8);
if (inputEncrypted % 2 == 0)
++inputEncrypted;
else
inputEncrypted = inputEncrypted + (13 + 13) + (11 + 11);
return inputEncrypted;
}
int decrypter(int inputEncrypted)
{
int decryptedNum = 0;
if (inputEncrypted % 2 == 1)
--inputEncrypted;
else
{
(11 - 11) - (13 - 13) - inputEncrypted;
}
decryptedNum = ((((inputEncrypted - 8) - 5) - 7) / 2);
return decryptedNum;
}请告诉我我能做些什么使它更好或者更好的设计!:)
发布于 2015-12-06 22:55:10
看上去这里有个bug:
其他{(11-11)-(13-13)- inputEncrypted;}
简化后,这个表达式变成:
else
{
-inputEncrypted;
}..。由于没有分配结果,所以inputEncrypted的值不变。如果您想否定变量的值,您必须这样写:
else
{
inputEncrypted = -inputEncrypted;
}我不知道这是否是您的真正意图(没有仔细查看您的代码)。但是原始代码完全不起任何作用,它被简化为一个结果不存储在任何地方的语句。
这可以简化如下:
如果(success == true && (redo == 'y‘success ==’Y“) keepGoing == true;否则keepGoing = false;
对此:
keepGoing = success && (redo == 'y' || redo == 'Y');注意您不需要编写x == true,您可以直接使用布尔表达式。
像whatToDoFunc这样的名字显然很糟糕。好的函数名对于理解程序是如何工作的是非常重要的。
发布于 2015-12-06 21:45:51
encrypterint encrypter(int input)
{
return (input * 2) + 21;
}和你的功能一样。为了达到这个目的,我做了以下工作:
x * 2 + 20总是偶数。decrypterdecrypter只是encrypter的反义词,所以:
int decrypter(int input)
{
return (input - 21) / 2;
}发布于 2015-12-07 07:39:04
unsigned int,而不是让它包装起来。否则,您将通过证明编译器“优化”代码会导致整数溢出,从而使代码“优化”。* 2操作是不可逆的,因为您可能会丢失信息。您正在移动的最高位应该放在第一个位上,使其成为一个位旋转操作。示例:如果您使用的是unsigned char,那么200 * 2 = 400 % 256 = 144和72 * 2 = 144,如果您想解密144,则不知道应该是200还是72。整数也是如此,只是用较大的数字。解决方案是使用位旋转,这有点尴尬,但是您可以检查一下这里。https://codereview.stackexchange.com/questions/113091
复制相似问题