【发布时间】:2020-07-13 12:21:54
【问题描述】:
我正在编写一个代码,其中我将每个字母移动一个位置,因此 (a) 变为 (b) 并且 (b) 变为 (c) 等等。到目前为止,我设法做到了,但我遇到了一个将大写字母 (Z) 环绕到 (A) 的问题。我似乎无法理解如何做到这一点的逻辑。 任何帮助,将不胜感激。 非常感谢。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(void)
{
//prompt the user to type in a text.
string p = get_string("plaintext: ");
//create a variable to refer to the length of the string.
int n = strlen(p);
for (int i = 0; i < n; i++)
{
//check if all chars (i) in the string (p) are alphabetical then increment i by 1.
if (isalpha(p[i]))
p[i]++;
{
//check if i has gone beyond the letter (z) and (Z).
if ((p[i] > 'z') && (p[i] > 'Z'))
{
//if so then subtract 26 letter after z or Z to get back to a or A.
p[i] = p[i] - 26;
}
}
printf("%c", p[i]);
}
printf("\n");
}
【问题讨论】:
-
你能把小写和大写分开处理吗?无论如何,请仔细考虑您的逻辑。
((p[i] > 'z') && (p[i] > 'Z'))- 其中一项测试必须是多余的,原因与(x > 10) && (x > 20)等同于仅检查x > 20相同。 -
问题在于
if条件,它检查您是否超出了“z”或“Z”。您将不得不根据情况打破条件。对于与此类似的小案例:if( smallCase(p[i]) & p[i]>'z') p[i]='a') -
char U[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int n = 20; n < 30; n++) putchar(U[n%26]);
标签: c cs50 caesar-cipher