2017-09-28 16 views
0

このコードは、単語を混乱させるプログラムの一部です。 forループがどのように動作しているのかを理解し、混乱した単語を作成するのに役立つ必要があります。たとえばtheWord = "apple"の場合、出力は以下のようになります:plpea。だから私はこの出力を作るためにforループで何が起こっているのか知りたい。ループの単語ジャンブルを理解する助けが必要

std::string jumble = theWord; 
    int length = theWord.size(); 
    for (int i = 0; i < length; i++) 
    { 
     int index1 = (rand() % length); 
     int index2 = (rand() % length); 
     char temp = jumble[index1]; 
     jumble[index1] = jumble[index2]; 
     jumble[index2] = temp; 
    } 
    std::cout << jumble << std::endl; 
+0

2つのランダムなインデックスを選択し、その2つのインデックスの文字を入れ替えます。 – Barmar

+0

コードのどの部分が混乱していますか? – Barmar

答えて

0

私は、forループの各行にコメントを追加します:

for (int i = 0; i < length; i++) // basic for loop syntax. It will execute the same number of times as there are characters in the string 
{ 
    int index1 = (rand() % length); // get a random index that is 0 to the length of the string 
    int index2 = (rand() % length); // Does the same thing, gets a random index 
    char temp = jumble[index1]; // Gets the character at the random index 
    jumble[index1] = jumble[index2]; // set the value at the first index to the value at the second 
    jumble[index2] = temp; // set the value at the second index to the vaue of the first 
    // The last three lines switch two characters 
} 

あなたはこのように考えることができ:文字列の各文字について、文字列に2つの文字を切り替えます。 また%(またはモジュラス演算子)は剰余を取得するだけですUnderstanding The Modulus Operator %

myString [index]はそのインデックスにある文字を返します。例: "Hello world" [1] == "e"

関連する問題