我开始学习C语言,所以我尝试用我所知道的方法制作一个简单的程序。程序应该要求一封信,询问你是否想要字母表中的字母位置(如果是这样,它会显示" x是字母表中的y字母"带有后缀)然后它会询问你是否想要二进制的字母并将其放入二进制文件中。但由于某种原因,它不起作用。我尝试了#34;手动调试"(使用puts()查看什么不起作用)和类#34; getNumber"但是当它进入主类时值会改变。
a returns "2686719" instead of "a is the 1st letter in the alphabet" and b returns "2b is the 2z\<<y in the alphabet".
这是代码,我做错了什么?
#include <stdio.h>
#include <stdlib.h>
//011
int main(){
int x = 2;
char letter;
puts("Write a letter");
char temp2;
scanf("%c", &temp2);
int number;
letter = temp2;
puts("get alphabet position? y/n ");
char temp[2];
scanf("%s", temp);
char answer = temp[0];
int tempNumber2 = getNumber(letter);
if(answer == 'y'){
char suffix[3];
int number = tempNumber2;
printf("%d", number);
if (number == 1){
x = 1;
suffix[0] = "s";
suffix[1] = "t";
}else if (number < 27){
suffix[0] = "t";
suffix[1] = "h";
x = 1;
}
if (x == 1){
printf("%c is the %d", letter, number);
printf("%s in the alphabet\n", suffix);
}}else if (answer == 'n'){
x = 1;
}else if (answer != 'y' && answer != 'n'){
puts("ERROR, invalid letter");
x = 3;
};
if(x != 3){
puts("Convert to binary?");
}
return 0;
}
int getNumber(letter){
char tempLetter = letter;
int tempNumber = -1;
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int i = 0;
while(i < 27){
i++;
if(tempLetter == alphabet[i]){
tempNumber = i;
tempNumber++;
printf("%d \n", tempNumber);
return tempNumber;
}
};
}
顺便说一下,我还没有达到二进制部分,因此它为什么是空的。
答案 0 :(得分:3)
正如评论中所说的那样,你的问题是后缀的最后一个字符没有设置为&#39; \ 0&#39;。
此外,你可以用更简单的方式getNumber
:
int getNumber(char letter) {
return (int)(letter - 'a') + 1;
}
顺便说一句,你可以让你的代码看起来更好一点(没有太多改变):
int main() {
char letter;
char answer;
puts("Write a letter");
scanf("%c", &letter);
getchar(); // read \n
puts("get alphabet position? y/n ");
scanf("%c", &answer);
getchar(); // read \n
if (answer == 'n') {
return 0;
}
if (answer != 'y') {
puts("ERROR, invalid letter");
return 1;
}
int number = getNumber(letter);
char suffix[3];
suffix[2] = 0;
if (number == 1) {
suffix[0] = 's';
suffix[1] = 't';
} else if (number == 2) {
suffix[0] = 'n';
suffix[1] = 'd';
} else if (number == 3) {
suffix[0] = 'r';
suffix[1] = 'd';
} else {
suffix[0] = 't';
suffix[1] = 'h';
}
printf("%c is the %d%s letter in the alphabet\n", letter, number, suffix);
puts("Convert to binary?");
return 0;
}