c - 使用模数循环 9-0 并打印

标签 c arrays modulo

目前我在我的程序中遇到一个问题,我正在尝试使用一种非常基本的加密方法,如果输入 5,则会打印 9。我试图让它循环,这样 z 会变成 d,9 会变成 3。我目前已经把它加了 4,但它没有从 9-0 开始循环,对于整数,对于字母,它工作正常。

下面是一段代码,由我的代码元素组成,用于重现正在发生的事情。

#include <stdio.h>
#include <conio.h>

int main()
{

int i, j;
char password[9];


printf("Please enter a password:\n\n");
scanf("%8c", &password);



for(i = 0; i < 8; i++)
    {
        if(password[i] >= '0' && password[i] <= '9')
        {
            password[i] = (char)(password[i] + 4 % 10);
        }

        if((password[i] >= 'a' && password[i] <= 'z') || (password[i] >= 'A' && password[i] <= 'Z') )
        {
            password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');
        }
    }

    for(j =  0; j < 8; j++)
    {
        printf("%c", password[j]);
    }

最佳答案

您必须以相同的方式处理数字和字母。你有:

        password[i] = (char)(password[i] + 4 % 10);
        ...
        password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');

您需要为数字减去和添加'0',就像您为字母做'a'一样:

        password[i] = (char)((password[i] - '0' + 4) % 10 + '0');
        ...
        password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');

关于c - 使用模数循环 9-0 并打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34135953/

相关文章:

c - 初始化元素在加载时不可计算

c - g_slice_new 不接受我的结构类型

将值转换为二进制值并将它们存储在数组中

java - 检查数字是否在特定序列中

c - 'stripspaces' 从指针生成整数而不进行强制转换

arrays - Protractor:将 ElementArrayFinder getTexts 存储在数组中并从方法返回数组

java - 随机数组值为空

java - 设置和显示名称和电子邮件 Java 对象类

java - Rabin-Karp 不适用于大素数(给出错误的输出)

java - Java 中 long 的模运算符是什么?