如何在c++中使用Switch用例
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";
}
在main中添加一个开关,并使每个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;
}
}
相关文章:
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 从父数组测试用例构造二叉树失败
- C++:Lambda 函数指针转换的用例是什么?
- 在Raspbian上编译pybind11测试用例时出现致命错误
- 对齐和对齐的实际用例C++关键字
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 某些测试用例未通过
- 改进基于模板的库的用例
- 函数覆盖有哪些用例?
- 如何在多个 Catch2 测试用例中检查相同的条件
- 函子还有更有用的用例吗?
- 在集合的情况下使用emplace_hint的用例是什么?
- 针对某些特定用例的C++原子内存排序
- 如何在不中断的情况下正确使用C++中的切换用例语句中的Fallthrough
- boost::hana 转发声明标头的用例是什么?
- 谷歌启动2018,测试用例中的整数错误
- 将指向数据成员的指针传递给 std::invoke 时有哪些用例和有用性?
- 如何在c++中使用Switch用例
- 将值转换为Switch语句用例
- 优化:switch语句中的用例顺序重要吗?