繁体   English   中英

我的 C 代码中不断出现分段错误

[英]I keep getting a segmentation fault in my C code

首先,我对 C 编程比较陌生,想编写一个程序,该程序能够接受用户输入,然后将其传递给 switch/case,并根据初始选择返回 output。 我能够在使用 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;
}


不知怎么的,无论输入什么,switch看的字符都变成了Q

但是,如果我替换这一行: char inputLet[1];

用这一行: char inputLet;

程序段错误。

任何帮助将非常感激。

printf("The letter you chose is: %s \n", inputLet);

当您使用char inputLet时,请使用%c 这是导致错误的原因。

而且,如果它是单个字符,则只需使用char inputLet而不是字符数组。

改完之后在本地测试得到这个output为'A'

Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation: 
A
HelloThe letter you chose is: A 
notLet here is: A 
Case1 reached! 
x has been set? Here: 4.00
Your equation evaluated to: 4.00 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM