打印菜单功能可在选择后继续打印

时间:2018-11-29 16:39:42

标签: c function switch-statement printf selection

伙计们,我原本应该制作一个程序,该程序将是一个使用函数来提供结果的计算器,但我搞清楚了它,并且一切正常,但是我在所有幽默的打印功能中都遇到了一个小问题,因为由于某些原因,无论何时程序打印出解决方案,我似乎都无法动手,它也打印出第一个选择。1.Add,我一生无法弄清楚为什么任何输入都会受到极大的感谢,谢谢你在这里是我的代码:

//Function to Add
int add (int a, int b);
//Function to Substract
int sub (int a, int b);
//Function to Multiply
int mul (int a, int b);
//Function to Divide
int div (int a, int b);
//Function to get remainder
int rem (int a, int b);
//Function to print menu
int printmenu();

//Begin main
int main()
{
    //Initialize Variables
    int num1=0;
    int num2=0;
    unsigned int selection =0;

    //Loop
    while ((selection=printmenu()) != 6)
    {
        switch (selection)
        {
        //Addition Case
        case 1: 
            printf("Enter two numbers: ");
            scanf("%d %d", &num1 , &num2 );
            printf("%d added to %d is %d",num1,num2,add(num1,num2));
            break;
        case 2:
            printf("Enter two numbers: ");
            scanf("%d %d", &num1 , &num2 );
            printf("%d substracted to %d is %d",num1,num2,sub(num1,num2));
            break;
        case 3:
            printf("Enter two numbers: ");
            scanf("%d %d", &num1 , &num2 );
            printf("%d multiplied to %d is %d",num1,num2,mul(num1,num2));
            break;  
        case 4:
            printf("Enter two numbers: ");
            scanf("%d %d", &num1 , &num2 );
            printf("%d divided to %d is %d",num1,num2,div(num1,num2));
            break;
        case 5:
            printf("Enter two numbers: ");
            scanf("%d %d", &num1 , &num2 );
            printf("%d divided to %d has a remainder of %d",num1,num2,rem(num1,num2));
            break;
        case 6:
            return 0;
        default:
            printf("That is not a valid choice.");
            break;
        }//End switch
    }//End while

    return 0;   
}//End main


//Function to add
int add (int a, int b)
{
    int total=0;
    total = a + b;
    return total;
}

//Function to substract
int sub (int a, int b)
{ 
    int total=0;
    total = a - b;
    return total;
}

//Function to multiply
int mul (int a, int b)
{
    int total=0;
    total = a * b;
    return total;
}

//Function to Divide
int div (int a, int b)
{
    int total=0;
    total = a / b;
    return total;
}

//Function to get Remainder
int rem (int a, int b)
{
    int total=0;
    total = a % b;
    return total;
}

//Function to Print Menu
int printmenu()
{
    int selection=0;
    //Print menu
    printf("1.Add\n");
    printf("2.Substract\n");
    printf("3.Multiply\n");
    printf("4.Divide\n");
    printf("5.Remainder\n");
    printf("6.Exit\n");
    printf("Selection: ");
    scanf("%d", &selection);
    return selection; 
}

1 个答案:

答案 0 :(得分:1)

打印操作结果时,在输出末尾不包括换行符。因此,当您打印菜单时,菜单的第一行将被打印在同一行上。

在每个结果打印语句的末尾添加\n,例如:

printf("%d added to %d is %d\n",num1,num2,add(num1,num2));