gpt4 book ai didi

c - 被 Caesar.c 困住了

转载 作者:行者123 更新时间:2023-11-30 20:54:41 25 4
gpt4 key购买 nike

我正在尝试运行 edx 编程简介中的程序分配 caesar.c。它需要一个能够使用凯撒加密来加密字符串的程序:因此,用户必须输入 key (命令行);例如, key 为 2 时,“A”字符需要用“C”字符加密;当您必须输入大于 26(字母的数量)的 key 时,问题就出现了。例如,对于键 27 和“A”字符,程序必须像键 1 一样返回“B”。

我尝试将字符的 ASCII 值转换为 0 到 26 之间的字母值,以便在 key 等于或大于 26 时使用模运算符。它返回给我一个段错误。谁能帮助我对错误原因提出一些建议?

这是程序:

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int key;

// function for an alphabetic value with non capital letters

int alpha_low( char c )
{
int alpha_value;
alpha_value = (int) c - 97;
return alpha_value + ( key % 26 );
}

// function to return to ascii valuee for non capital letters

char ascii_low( char c )
{
return (char) alpha_low( c ) + 97;
}

// function for an alphabetic value with capital letters

int alpha_up( char c )
{
int alpha_value;
alpha_value = (int) c - 65;
return alpha_value + ( key % 26 );
}

// function to return to ascii value for capital letters

char ascii_up( char c )
{
return (char) alpha_up( c ) + 65;
}


int main(int argc, string argv[])
{
int result;
string p;
key = atoi( argv[1] );

if( argc != 2 || key < 0 )
{
printf("Usage: ./caesar key(positive integer)\n");
return 1;
}

printf("Please, write a plaintext: ");
p = GetString();

for( int i = 0, n = strlen(p); i < n; i++)
{
if ( isalpha(p[i]) )
{
if ( islower(p[i]) )
{
result = alpha_low( p[i] );
printf("%c", ascii_low( p[i] ));
}
else if( islower( p[i]) )
{
result = alpha_up( p[i] );
printf("%c", ascii_up( p[i]) );
}
}
}

return 0;
}

最佳答案

凯撒字母字符的函数应该类似于(按基本步骤分解):

int caesar_lower(int c,int key) {
int v = c-'a'; // translate 'a'--'z' to 0--25
v = v+key; // translate 0--25 to key--key+25
v = v%26; // translate key--key+25 to key--25,0--key-1
v = v+'a'; // translate back 0--25 to 'a'--'z'
return v;
}

关于c - 被 Caesar.c 困住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com