2016-04-16 5 views
-4

このコードでスイッチケースを使用するにはどうすればよいですか?私は何度も試してみましたが、実際にエラーなくそれを作る方法は分かりません。C++でスイッチケースを使用するには?

#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"; 
} 
+1

http://en.cppreference.com/w/cpp/language/switch –

+0

あなたのコードをインデントしてください:それは良い習慣です – bibi

答えて

1

メインでスイッチを追加し、それぞれのcase文を関数呼び出し(link 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; 
} 
} 
関連する問題