if语句中的逻辑运算符c ++

时间:2016-09-12 06:24:12

标签: c++ string if-statement logical-operators

底部的当前代码有效但我无法将if语句组合到一个我不希望它们发生的位置。加密应该只是字母值。资本和小写的z应该循环到A.我有一位老师,但她不知道所以我会感激任何帮助。谢谢< 3

这不起作用......

if (sentence[i] == 'z' || 'Z')
{
sentence[i] = sentence[i] - 26;
}

这不起作用

if (sentence[i] == 'z' || sentence[i] == 'Z')
{
sentence[i] = sentence[i] - 26;
}

这很有效。

if (sentence[i] == 'z')
{
sentence[i] = sentence[i] - 26;
}
if (sentence[i] == 'Z')
{
sentence[i] = sentence[i] - 26;
}

完整代码。

#include <iostream>
#include <string>

using namespace std;

class EncryptionClass
{
    string sentence;

public:

    //constructors
    EncryptionClass(string sentence)
        {setString(sentence);}
    EncryptionClass()
        {sentence = "";}

    //get and set
    string getString()
        {return sentence;}
    void setString(string sentence)
        {this-> sentence = sentence;}

    //encrypt
    void encryptString()
    {
        for(int i = 0; i < sentence.length(); i++)
        {
            if (isalpha(sentence[i]))
            {

                if (sentence[i] == 'z')
                {
                    sentence[i] = sentence[i] - 26;
                }
                if (sentence[i] == 'Z')
                {
                    sentence[i] = sentence[i] - 26;
                }

                sentence[i] = sentence[i] + 1;
            }
        }
    }
};

int main()
{
    string sentence;
    cout << "Enter a sentence to be encrypted. ";
    getline(cin, sentence);
    cout << endl;

    EncryptionClass sentence1(sentence);
    cout << "Unencrypted sentence." << endl;
    cout << sentence1.getString() << endl << endl;
    sentence1.encryptString();
    cout << "Encrypted sentence." << endl;
    cout << sentence1.getString() << endl;


    cin.get();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

在你的情况下,两个If语句都应该是平等的。

if (sentence[i] == 'z' || sentence[i] == 'Z')
{
    sentence[i] = sentence[i] - 26;
}

if (sentence[i] == 'z')
{
    sentence[i] = sentence[i] - 26;
}
if (sentence[i] == 'Z')
{
    sentence[i] = sentence[i] - 26;
}

情况并非总是如此

摘录2:如果您更改isentence[i]的值,则第二个if的行为会有所不同。 如果您将减少值32,则两个片段的行为将不同

char myChar = 'z'
if (myChar == 'z' || myChar == 'Z')
{
    myChar = myChar - 32;
}
// myChar is now 'Z'

char myChar = 'z'
if (myChar == 'z')
{
    myChar = myChar - 32;
}
// myChar is now 'Z'
if (myChar == 'Z')
{
    myChar = myChar - 32;
}
// myChar is now ':' 

答案 1 :(得分:0)

问题是你应该从你的价值中扣除 25 ,而不是 26 !这是因为字母表中有26个字母,从025(包括)相对编号。要从最后一个字母(数字0)到达第一个字母(数字25),您需要扣除 25

A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

但是除了第一个版本之外的每个版本都应该给出相同的结果。

#include <iostream>

int main()
{
    char sentance[] = "Zz";

    for(int i = 0; i < 2; ++i)
    {
        if(sentance[i] == 'Z' || sentance[i] == 'z')
        {
            sentance[i] = sentance[i] - 25;
            std::cout << "letter " << i << " = " << sentance[i] << '\n';
        }
    }
}

<强> Run it here