c - 使用 int 数组作为 switch case

标签 c arrays switch-statement

我对 C 相当陌生,我正在尝试使用 int 数组作为这样的开关的选项号

void totalEntered(float * total, float * inputFigure)
{
    *total = *total + *inputFigure;
}

int main()
{
    float amountEntered = 0.00;
    float tot = 0.00;
    int option_numbers[3] = {1,2,3,4};
    float a_food = 0.00;
    float a_tab = 0.00;
    float a_trav = 0.00;
    float a_bill = 0.00;

    totalEntered(&tot, &amountEntered);



    printf("Please enter option number from below \n1.food\n2.tabacco\n3.travel\n4.bills\n");
    scanf("%i", option_numbers);
    switch(option_numbers)
    {
    case 1:
        printf("Please Enter an amount: ");
        scanf("%f", amountEntered);
        a_food = a_food + amountEntered;
        totalEntered(&tot, &amountEntered);
        printf("You have spent %f on food", a_food);
        break;
    case 2: /*ignore below haven't finish that*/
        a_tab = a_tab + amountEntered;
        printf("You have spent %.2f on tabacco", a_tab);
        break;
    case 3:
        a_trav = a_trav + amountEntered;
        printf("You have spent %.2f on travel", a_trav);
        break;
    case 4:
        a_bill = a_bill + amountEntered;
        printf("You have spent %.2f on travel", a_bill);
        break;
    default:
        printf("You have not input a category!");
        break;
    }
    return 0;


}

任何人都可以建议如何解决这个问题...我有点卡住了! :D 我试图让用户选择一个数字,如果用户想在食物下输入一个金额,他/她必须选择选项 1,然后选择一个金额。希望这比以前更有意义! 谢谢

最佳答案

您无法将数组传递给 switch(),您需要传递数组中的元素之一:

int item = 2; // or whatever

switch(option_numbers[item])
{
<小时/>

编辑:
根据您的评论,如果您想接受用户输入并让他们选择 4 个选项之一,这非常简单,完全不需要该数组。

int selection = -1;
printf("Which option do you want? (1-4): ");
scanf("%d", &selection);

switch(selection)
{
<小时/>

旁注:

int option_numbers[3] = {1,2,3,4}; // that's not size 3, it's got 4 elements should 
                                   // have been:
                                   // int option_numbers[4] = {1,2,3,4}; 

关于c - 使用 int 数组作为 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15391182/

相关文章:

c - 如何使用makefile以及 "no such jobs "是什么意思

Javascript:将某些信息推送到数组并从数组中获取信息

Java列表比较导致错误我无法确定

php - 在数组中设置嵌套项

java - 为什么我要在 switch 语句上使用责任链

java - Android:在 Switch 语句中嵌套 for 循环以获取 ArrayList 的总和

ruby-on-rails-3 - 警告 : else without rescue is useless?

c - 哪种语言有助于为有效的 C 程序创建报告

无法让多数组在 c 中工作

c - 为什么 while 循环中的这条语句从未被执行?