gpt4 book ai didi

c - Switch 启动时默认运行

转载 作者:行者123 更新时间:2023-11-30 17:47:42 27 4
gpt4 key购买 nike

(代码是C语言)

出于某种原因,我的代码总是在打印菜单之前执行“默认”部分中列出的内容。

#include <stdio.h>

int main(){
double funds=0; //initial funds
double donation=0; //donation to funds
double investment=0; //amount invested
int choice=0; //for the switch
int countdonate=0; //counts number of donations
int countinvest=0; //counts number of investments

printf("How much money is in the fund at the start of the year? \n");
scanf("%lf", &funds);//sets initial funds


while (choice!=4)

{

switch (choice)

{ case 1: //option for donating
printf("How much would you like to donate? \n");
scanf("%lf", &donation);
funds=funds+donation;
countdonate++;
break;

case 2: //option for investing
printf("How much would you life to invest? \n");
scanf("%lf", &investment);
if (investment>funds){
printf("You cannot make an investment of that amount \n");
break;}
else{
funds=funds-investment;
countinvest++;
break;}

case 3: //prints current balance, number of donations, and number of investments
printf("The current balance is %.2lf \n", funds);
printf("There were %d donation(s) and %d investment(s) \n", countdonate, countinvest);
break;


default: //if the user selections something that isnt listed
printf("why is this printing \n");
break;
}


//displays list of options
printf("What would you like to do? \n1 - Make a donation \n2 - Make an investment \n3 - Print balance of fund \n4 - Quit \n");
scanf("%d", &choice);

//quit option, outside of the loop.
//prints current balance, number of donations, number of investments, and ends the program
if (choice==4)
{printf("The current balance is %.2lf \n", funds);
printf("There were %d donation(s) and %d investment(s) \n", countdonate, countinvest);
}

}

return 0;
}

所以当我第一次运行它时,它会打印:

<小时/>

年初时基金里有多少钱?1000(我输入一个整数)为什么这样打印(这是在默认部分中,不应该打印)你想干什么?1 - 捐款2 - 进行投资3 - 打印资金余额4 - 退出

<小时/>

如何解决这个问题?

最佳答案

初始选择值为 0,因此 switch 语句打印出您不期望的内容。要解决此问题,您应该如图所示移动下面的开关。还要在 if (choice == 4) 中添加中断。

//quit option, outside of the loop.
//prints current balance, number of donations, number of investments, and ends the program
if (choice==4)
{printf("The current balance is %.2lf \n", funds);
printf("There were %d donation(s) and %d investment(s) \n", countdonate, countinvest);
break;
}

switch (choice)
...

关于c - Switch 启动时默认运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840427/

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