【发布时间】:2020-09-02 07:26:46
【问题描述】:
首先,我对 C 编程比较陌生,想编写一个能够接受用户输入然后将其传递给 switch/case 并根据初始选择返回输出的程序。我可以在使用 int 数据类型时做到这一点,但我希望在将输入作为 char 时得到一些帮助。
#include <stdio.h>
double x = 1;
double y = 3;
char inputLet[1];
double chooseEquation(char notLet){
char notNotLet = notLet;
printf("notLet here is: %c \n", notLet);
switch(notLet){
case 'A':
x += y;
printf("Case1 reached! \n");
break;
case '2':
x += -y;
break;
case '3':
x -= y;
break;
case '4':
x -= -y;
break;
case '5':
x *= y;
break;
case '6':
x *= -y;
break;
default :
printf("defaulting! btw: %c \n", notNotLet);
x = 0;
}
printf("x has been set? Here: %.2f\n", x);
return x;
}
int main(){
printf("Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation: \n");
scanf(" %c", &inputLet);
printf("The letter you chose is: %s \n", inputLet);
double outputLet = chooseEquation(inputLet);
printf("Your equation evaluated to: %.2f \n", outputLet);
return 0;
}
不知怎么的,不管输入什么,开关看的字符都变成了Q
但是,如果我替换这一行:
char inputLet[1];
用这一行:
char inputLet;
程序分段错误。
任何帮助将不胜感激。
【问题讨论】:
-
%c是单个char的说明符,%s是空终止char数组的说明符。不要混合它们,它们使用不同的类型 -
并且
double outputLet = chooseEquation(inputLet);行至少应该给出编译器警告,因为您传递的是char*,而函数需要char -
@UnholySheep 好吧,这就是为什么我提到我的编辑,我删除了应该使其成为单个 char 数据类型的 [1],然后导致上述分段错误。
-
向您说明的一点是
printf("The letter you chose is: %s \n", inputLet);是错误的,因为%s需要一个字符串。inputLet是单个字符数组,它不是字符串(因为它不是以 NULL 结尾的序列)。 -
如果你从声明中删除
[1],那么printf("The letter you chose is: %s \n", inputLet);应该会抱怨——因为你在这里有%s而不是%c