簡體   English   中英

如何在 C++ 中使用 Switch case?

[英]How to use Switch case in c++?

如何在此代碼中使用 switch case? 我已經嘗試了幾次,但我真的不知道如何做到沒有錯誤。

#include<iostream.h>
int x,y;
int sum(int a,int b)
{
    int c;
    c = a+b;
    return (c);
}
int sub (int a ,int b)
{
    int c;
    c = a-b ;
    return (c);
}
int multi ( int a, int b )
{
    int c ;
    c = a*b;
    return (c);
}
float div ( int a , int b)
{
    float c;
    c = a/b ;
    return (c);
}
main()
{
    cout<<"enter the value of x = ";
    cin>>x;
    cout<<"enter the value of y = ";
    cin>>y;
    cout<<"x + y  = "<< sum(x,y);
    cout<<"\n x - y  = "<< sub(x,y);
    cout<<"\n x * y  = "<< multi(x,y);
    cout<<"\n x /y  = "<< div (x,y);
    cin>>"\n";
}

在您的主文件中添加一個開關,並使每個 case 語句成為一個函數調用(鏈接 sum()、multi() 等)。

你想要什么 :

#include <iostream>
using namespace std;

int x,y;
int sum(int a,int b)
{
int c;
c = a+b;
return (c);
 }
int sub (int a ,int b)
{
int c;
c = a-b ;
return (c);
 }
int multi ( int a, int b )
{
int c ;
c = a*b;
return (c);
}
float div1( int a , int b)
{
float c;
    c = a/b ;
return (c);
}
main()
{
    int ch=0;
std::cout <<"enter the value of x = ";
std::cin >>x;
std::cout <<"enter the value of y = ";
std::cin >>y;
std::cout <<"Input"<<std::endl;
std::cout <<"Sum: 1, Subtract: 2, Product: 3, Divide: 4"<<std::endl;
std::cin >>ch;
switch(ch){
 case 1: 
    std::cout <<"x + y  = "<< sum(x,y) <<std::endl;break;
 case 2: 
    std::cout <<"x - y  = "<< sub(x,y) <<std::endl;break;
 case 3: 
    std::cout <<"x * y  = "<< multi(x,y) <<std::endl;break;
 case 4: 
        if(y!=0){
            std::cout <<"x /y  = "<<div1(x,y)<<std::endl;
        } else { 
            std::cout <<"Denominator can't be zero is 0"<<std::endl;
     }
     break;
 default:
    std::cout <<std::endl;
}
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM