先看一串代码
int a,b,x,y;
cin>>a>>b;
if(a>b)
x=a+b;y=a-b;
else
x=a-b;y=a+b;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a,b,x,y;
cin>>a>>b;
if(a>b){
x=a+b;
y=a-b;
}
else{
x=a-b;
y=a+b;
}
cout<<x<<' '<<y<<endl;
}
第一串代码错误:
if后面未加{}那么y=a-b;都会输出
else后面未加{}一样y=a+b;都会输出 //这个要注意
用if语句算三角形面积:
#include <iostream>
#include <cmath> //用到数学算法
using namespace std;
int main()
{
double z,x,c;
cin>>z>>x>>c;
if(z+x>c&&z+c>x&&x+c>z){
double s,t;
t=(z+x+c)/2.0;
s=sqrt(t*(t-z)*(t-x)*(t-c));//求三角形面积
cout<<"area="<<s<<endl;
}
else
cout<<"error"<<endl;
return 0;
}
z+x>c&&z+c>x&&x+c>z这个需要三个都满足也就是两边之和大于第三边
面积计算公式:
t=(z+x+c)/2.0;
s=sqrt(t*(t-z)*(t-x)*(t-c));
如果switch(x),x不在下面语句中则执行default语句
default放的位置不同结果不同
也可以直接用break直接输出:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int g;
cin>>g;
switch (g)
{
case 1:cout<<"85-100\n";break;
case 2:cout<<"70-84\n";break;
case 3:cout<<"60-69\n";break;
case 4:cout<<"0-59\n";break;
default:cout<<"error"<<endl;
}
return 0;
}
输入1234可以得到相应的分数范围
注意:如果case后面改为'a','b','c','d',需要把上面int改为char
最后测试:
用if语句写下面分段函数
答案:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int x,y;
cin>>x;
if(x<-3)y=x-1;
else
if(-3<=x && x<=3)y=9-x*x;
else
if(x>3)y=x+1;
cout<<y<<endl;
return 0;
}