條件判斷

簡單來說就是if else

不知道聊什麼就聊天氣

先來看看邏輯

如果下雨帶傘

如果放晴不帶傘

我知道你很急但你先別急

來看程式囉

if-else if-else

把握這個原則就好

if(條件1)
{
  條件1成立時執行;
}
else if(條件2)
{
  條件1不成立條件2成立時執行;
}
else if(條件3)
{
  條件1、條件2皆不成立但條件3成立時執行;
}
else
{
  條件123皆不成立時執行;
}

任一條件成立就不會往下判斷囉

#include<iostream>
using namespace std;
int main()
{
  bool rain=false;
  if(rain==true)
    cout<<"帶傘"<<endl;
  else
    cout<<"不帶傘"<<endl;
  return 0;
}

不帶傘

#include<iostream>
using namespace std;
int main()
{
  string light="red";
  if(light=="green")
    cout<<"走"<<endl;
  else if(light=="yellow")
    cout<<"趕快走"<<endl;
  else
    cout<<"沒有警察趕快走"<<endl;
  return 0;
}

沒有警察趕快走

上面兩個情況可以全部用if

不用else if也不會影響結果

但什麼情況下會影響呢?

條件的重疊性

如果ㄌㄌ今天要領補習班的獎學金......

>=60=60元

>=70=70元

>=80=80元

>=90=90元

100=100元

#include<iostream>
using namespace std;
int main()
{
  int grade=100;
  int money;
  if(grade==100)
    money=100;
  if(grade>=90)
    money=90;
  if(grade>=80)
    money=80;
  cout<<money<<endl;
  return 0;
}

80

#include<iostream>
using namespace std;
int main()
{
  int grade=100;
  int money;
  if(grade==100)
    money=100;
  else if(grade>=90)
    money=90;
  else if(grade>=80)
    money=80;
  cout<<money<<endl;
  return 0;
}

正確寫法是這樣子ㄉ

if - if => 即使第一個if成立 仍舊會執行第二個if

if - else if =>若第一個if成立 則不會執行第二個if

else的意思是"其他的"

所以在"如果(if)"不成立的情況下才會去找"其他的如果(else if)"

結論

  • 注意條件的重疊性
  • 注意條件的順序
  • 可以使用多個else if

TRY TRY SEE

一點補充

switch case和三元運算子

switch-case-default

基本上只是換個字而已

#include<iostream>
using namespace std;
int main()
{
  char light='r';
  switch (light)
  {
    case 'g'://case後面只能接整數或字元喔
      cout<<"走"<<endl;
      break;//用break達到else if的效果(不往下判斷)
    case 'y':
      cout<<"趕快走"<<endl;
      break;
    default://default就是else
      cout<<"沒警察趕快走"<<endl;
      break;
  }
}

三元運算子

程式會比較乾淨而且很帥

a?b:c
//若a為真 執行b 否則執行c
#include<iostream>
using namespace std;
int main()
{
  int grade=59;
  cout<<(grade>=60?"pass":"fail");
  return 0;
}

KAHOOT

條件判斷

By ㄌㄌ

條件判斷

  • 56