if语句中的逻辑运算符

logical operators in if statements c++

本文关键字:逻辑运算符 语句 if      更新时间:2023-10-16

当前的代码在底部工作,但我不能结合if语句不移动ascii值到一个位置,我不希望他们是。加密应该只有字母值。大写和小写的z应该绕着a转。我有一个老师,但她不知道,所以我会很感激任何帮助。谢谢& lt; 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;
}

在这种情况下,两个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 ':' 

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

      A B C D E F G H J J K L M M N O P P Q R R T U V W X Y Z0 12 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';
        }
    }
}

在这里运行