【问题标题】:Default in Switch running at the start默认在 Switch 启动时运行
【发布时间】:2013-09-21 08:03:06
【问题描述】:

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


我该如何解决这个问题?

【问题讨论】:

  • choice == 0 在循环之前,并且您没有读取任何内容来重置它,因此 switch 语句进入默认情况。

标签: c switch-statement default


【解决方案1】:

初始选择值为 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)
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多