คำตอบที่ได้รับเลือกจากเจ้าของกระทู้
ความคิดเห็นที่ 6
ประเด็นที่ควรทราบคือ
1. char จริง ๆ ก็คือ ตัวเลข -127 ถึง 127
2. 'A' - 'Z' เป็นชุดตัวเลขที่เรียงต่อกัน และ 'a' - 'z' เป็นชุดตัวเลขที่เรียงต่อกัน ascii.cl
3. char กับ int สามารถทำการคำนวณต่อกันได้ เช่น 'A' + 10 หรือ 'A' - 'A' = 0 หรือ 'Z' - 'A' = 25
4. อัลกอริทึม Caesar Cipher เถอะครับ อย่าไป reinvent the wheel
จริง ๆ โจทย์ที่อาศัย algorithm ที่เค้าใช้ ๆ กันอยู่แล้วอะไรแบบนี้
น่าจะใบ้ keyword ให้นัก'สาไปค้นหน่อยนะ
หรือว่าไม่ได้เข้าแล้วโดนวางยา
เอ่อ...ก็ไปเคลียร์กันเองนะครับ
1. char จริง ๆ ก็คือ ตัวเลข -127 ถึง 127
2. 'A' - 'Z' เป็นชุดตัวเลขที่เรียงต่อกัน และ 'a' - 'z' เป็นชุดตัวเลขที่เรียงต่อกัน ascii.cl
3. char กับ int สามารถทำการคำนวณต่อกันได้ เช่น 'A' + 10 หรือ 'A' - 'A' = 0 หรือ 'Z' - 'A' = 25
4. อัลกอริทึม Caesar Cipher เถอะครับ อย่าไป reinvent the wheel
จริง ๆ โจทย์ที่อาศัย algorithm ที่เค้าใช้ ๆ กันอยู่แล้วอะไรแบบนี้
น่าจะใบ้ keyword ให้นัก'สาไปค้นหน่อยนะ
หรือว่าไม่ได้เข้าแล้วโดนวางยา
เอ่อ...ก็ไปเคลียร์กันเองนะครับ
แสดงความคิดเห็น
ช่วยดูcodeภาษาซีให้หน่อยครับ
ให้ทำโดยใช้ user-fined function
Enter shift amount (1-25): 3
Enter message: Hello World@
Encrypted message: Khoor Zruog
Enter shift amount (1-25): 23
Enter message: Khoor Zruog1*3@
Encrypted message: Hello World1*3
นี่คือ code ที่ผมคิด
#include <stdio.h>
char shiftByN(char org[],int n);
int size=26; // number of A-Z
int main ()
{
int n;
char character[100];
do
{
printf("Enter shift amount (1-25):\n");
scanf("%d",&n);
}while(!(n>=1&&n<=25));
printf("Enter message:\n");
gets(character);
gets(character);
printf("Encrypted message:\n");
shiftByN(character,n);
}
char shiftByN(char org[],int n)
{
int i;
char shift;
for(i=0;org!='@';i++)
{
shift=org+n;
while((org>=65&&org<=90)&&
{
shift=shift-size;
}
while((org>=97&&org<=122)&&
{
shift=shift-size;
}
if(shift<=90&&shift>=65||shift<=122&&shift>=97)
printf("%c",shift);
if (org==' ')
printf(" ");
if(org>=1&&org<=67)
printf("%c",org);
}
}
output คือ
Enter shift amount (1-25): 3
Enter message: Hello World@
Encrypted message: Khoor Zruog (รันตรงตามโจทย์)
แต่ กลับกันมันรันคนละตัวอักษร
แล้วผมก็ลองรัน
Enter shift amount (1-25): 25
Enter message: ABCDEFGHIJKLMNOPQRSTUVWXYZ@
Encrypted message: ZAABBCCDEFGHIJKLMNOPQRSTUVWXYZ (มั่วมาก)
Enter shift amount (1-25): 25
Enter message: abcdefghijklmnopqrstuvwxyz@
Encrypted message: zabcde (ถูกแต่หยุดที่'e')