if语句中的逻辑运算符
logical operators in if statements c++
当前的代码在底部工作,但我不能结合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:如果您更改i
或sentence[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个字母,相对编号从0
到25
(包括)。要从最后一个字母(数字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'; } } }
在这里运行
相关文章:
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 逻辑运算符上出现错误代码 a')'
- 将 OR 逻辑运算符从 C++ 转换为 Fortran
- 我需要这方面的帮助C++在使用逻辑运算符时是/否问题
- C++复合逻辑运算符不使用比较运算符
- (C++)为什么"||"逻辑运算符返回 1?
- 逻辑运算符的问题。主要对 && 和 || 感到困惑
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- std::查找多个元素和逻辑运算符
- 逻辑运算符及其在C/C 中的优先级
- 括号和逻辑运算符
- 如何在 C++ 中使用更多逻辑运算符
- 引用、逻辑运算符和循环条件
- 在 switch 语句中使用算术和逻辑运算符
- 读取真值表C++的逻辑运算符表达式
- C++逻辑运算符 Q
- 关于 while(n) 在 c++ 中没有逻辑运算符
- if语句中的逻辑运算符
- if语句中的逻辑运算符
- if 语句 - C++逻辑运算符