2011-10-15 160 views
1

所以我試圖加密一個四位數的整數,在數字中加上七,然後將整數除以十。在我的計劃中,我分別取每個數字,然後我需要將整個數字除以十。我怎樣才能將所有單獨的int整合成一個四位數字?加密數字C++

#include "stdafx.h" 
using namespace std; 

int main() 
{ 
    //Define all variables needed 
    int a,b,c,d,enc,ext; 

    //Print dialog and input each single digit for the four number digit 
    cout << "Enter Your First Digit:" << endl; 
    cin >> a; 
    cout << "Enter Your Second Digit:" << endl; 
    cin >> b; 
    cout << "Enter Your Third Digit:" << endl; 
    cin >> c; 
    cout << "Enter Your Fourth Digit:" << endl; 
    cin >> d; 
    //Add seven to each digit 
    a += 7; 
    b += 7; 
    c += 7; 
    d += 7; 

    a /= 10; 
    b /= 10; 
    c /= 10; 
    d /= 10; 

    cout << "Your encrpyted digits:" << c << d << a << b <<endl; 

    cout << "Enter 1 to exit:" <<endl; 
    cin >> ext; 

    if (ext = 1) { 
     exit(EXIT_SUCCESS); 
    } 
} 

正如您可能注意到的那樣,我將每個數字分開。我需要一起做。然後我還創建了一個解密,我將在單獨的程序中讓我回到原始數字。

+2

'if(ext == 1)'。您需要使用'=='運算符,但不要使用'='運算符。 '='用於賦值而不用於邏輯比較。這個問題有點不清楚。你能解釋一下,你會爲​​a,b,c,d選擇什麼樣的輸入? – Mahesh

+0

「將它們分在一起」是什麼意思? – Mat

+0

這是功課嗎?如果是這樣,請相應標記。 – Uffe

回答

1

個人數字組合成一個四位數字簡單;將第一位數字乘以1000,將第二位乘以100,依此類推。

但是這是一種單向算法;您將永遠無法從中檢索原始的四位數字。

1

這是youd'd可能會尋找:

int e = (a*1000)+(b*100)+(c*10)+d; 
e=e/10; 
+0

,如果你願意,你也可以在這一步本身中加入7。 – COD3BOY

+0

謝謝!我也被告知這不是加密。我想跟着我的書,但有麻煩。 –

0

從描述中不清楚加法是否應該是模10;如果是這樣

((((((a % 10) * 10) + (b % 10)) * 10) + (c % 10)) * 10) + (d % 10) 

如果你不想模10

(((((a * 10) + b) * 10) + c) * 10) + d 
4

基於您的評論你正在嘗試做的Caesar Cipher的變化,在這種情況下,你應該使用模運算符(%)不是整數除法運算符(/)。使用整數除法會丟失將阻止您解密的信息。當你的數字位於{0,1,2}時,你的分區結果爲0.當它位於{3,4,5,6,7,8,9}時,分區結果爲1.你不能將{0,1}解密成原始數字,而不需要一些額外的信息(你已經丟棄了這些信息)。

如果要使用凱撒密碼方法逐位進行加密,則應該使用modulo arithmetic,以便每個數字都有唯一的加密值,可以在解密過程中進行檢索。如果這真的是你正在尋找的,那麼你應該做一些像下面有7加密:

a = (a + 7) % 10; 
    b = (b + 7) % 10; 
    c = (c + 7) % 10; 
    d = (d + 7) % 10;

要decrpyt,您可以通過3減去7,這在模10算術加法,從而使將是:

a = (a + 3) % 10; 
    b = (b + 3) % 10; 
    c = (c + 3) % 10; 
    d = (d + 3) % 10;

這當然預示着你已經正確驗證了你的輸入(在你上面的例子中不是這種情況)。

0

忽略一個事實,即你幾乎可以肯定需要mod而不是除法(正如@Andand所說的那樣),有多種方法可以將數字轉換爲數字!

現在很多使用解釋型語言的人可能會想要象徵性地做到這一點。 C++可以做到這一點,還算整齊的事實:

// create a string stream that you can write to, just like 
// writing to cout, except the results will be stored 
// in a string 

stringstream ss (stringstream::in | stringstream::out); 

// write the digits to the string stream 
ss << a << b << c << d; 

cout << "The value stored as a string is " << ss.str() << endl; 

// you can also read from a string stream like you're reading 
// from cin. in this case we are reading the integer value 
// that we just symbolically stored as a character string 

int value; 
ss >> value; 

cout << "The value stored as an integer is " << value << endl; 

它不會因爲往返爲字符串,並回作爲一個4位數字的這條狹窄的情況下,乘法一樣高效。但很高興知道這項技術。而且這是一種編碼風格,可以更容易地進行維護和適應。

如果您#include <sstream>,您將得到stringstream。