c语言 - 有没有办法在 if 语句中输入"但是"?



在我的CS50课程中,我正在制作一个程序,该程序根据用户输入的字符对消息进行加密。

如果用户输入 3,则消息的每个字母向右移动 3 个单位。为此,我将这些字母转换为ASCII码。遗憾的是,当用户尝试使用任何形式的 Z 加密任何消息时,用户会被发回一个特殊字符,例如括号或括号。当原始 ASCII 代码加上密钥(由用户输入(大于 90 或大于 122 时,也会发生这种情况。ASCII 代码 90 是 Z,122 是 z。为了解决这个问题,我设置了一个条件,当 ASCII 代码大于 90 或 122 时,减去键的值。这当然也不起作用,因为当输入诸如 a 之类的值时,键的值为 3。例如:当用户输入 ZzAa 时。除 a 之外的每个字母都加密为一个字母。另一方面,"a"被加密为"^"。原因是 a 在 ASCII 代码中是 97,97 大于 90 而不是 122,因此它被减少到 94,即"^"。

我想知道if语句中是否有"but"条件,所以我可以把条件:大于 90 但小于 97,这样 (97( 就不会减少到 94 (^(

我尝试输入逻辑 OR 和逻辑 AND。他们似乎都不起作用。它不起作用的一个例子是当您输入 3 作为密钥并将 ZzAa 作为正在加密的测试消息时。

#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
if (argc != 2)
// If the user uses the program incorrectly, it shows them how to do it and quits the program
{
printf("Usage : ./caesar keyn");
return 1;
}
// stores the second value inputted by the user(key) into an integer key
int key = atoi(argv[1]) % 26;
char *ptext = get_string("Plaintext : ");
for (int i = 0, n = strlen(ptext); i < n; i++)
{
if(ptext[i] + key >= 90 || ptext[i] >= 122)
{
printf("Cipher text: %cn ", ptext[i] - key);
printf("Cipher text: %in ", ptext[i] - key);
}
else
{
printf("Cipher text: %cn ", ptext[i] + key);
printf("Cipher text: %in ", ptext[i] + key);
}
}
return 0;
}

This worked for the most part

使用括号对相互包含的逻辑表达式进行分组。您的but实际上是一个and(&&(,如下所示:

if( ( ptext[i] + key >= 90 && ptext[i] + key < 97 ) || ptext[i] >= 122 )
{
// etc
}

也就是说,我会使用一个中间变量,这样读者就可以立即清楚发生了什么:

const char clear   = ptext[i];
const char shifted = ptext[i] + key;
if( ( clear => 90 && clear < 97 ) || shifted >= 122 ) 
{
// etc
}

或者考虑引入命名布尔值以使代码自记录:

#include <stdbool.h>
...
const char clear   = ptext[i];
const char shifted = ptext[i] + key;
const bool isAscii        = clear => 90 && clear < 97;
const bool isOutsideRange = shifted >= 122;
if( isAscii || isOutsideRange ) 
{
// etc
}

(请注意,在大多数编程语言(以及几乎所有编译语言(中,中间变量根本不会损害性能,因为编译器足够聪明,知道它们根本不会改变函数的实际行为。有时他们甚至可以使程序更快,因为编译器可以推断出更多关于你的意图的信息(。

相关内容

最新更新