0

(代码在 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 - 退出


我该如何解决?

4

1 回答 1

0

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

//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)
...
于 2013-09-17T02:48:19.507 回答