gpt4 book ai didi

c - 使用 int 数组作为 switch case

转载 作者:行者123 更新时间:2023-11-30 20:45:30 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com