第三章條件判斷程序

今年是2014年編寫程序判斷今年是閏年還是平年。

Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png

為什么不能對num初始化 int num = 0;

Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
#include<stdio.h>
int main(void)
{
   int year =2014;
   
   if()
   {
      printf(")
   {
   else
   {
      printf(")
   }

C語言中的三目運算符:“?:”,其格式為:
** 表達(dá)式1 ? 表達(dá)式2 : 表達(dá)式3;**

檢查條件

這個程序讓用戶輸入一個1~10之間的數(shù)字,再確定該數(shù)字有多大。

 //program 3.1 A simple example of the if statement
             #include<stdio.h>

             int  main (void)'
             { 
               int  number  = 0 ;    //初始化為0,分號為英文下的
               printf("\n Enter an integer between 1 and 10: ");
               scanf("%d",&number);

               if( number > 5 )
               printf(" You entered  %d which is greater  than 5\n", number);

                if (number < 6)
                printf("You entered %d which is less  than 6\n", number);
                return   0 ;
              }

使用IF語句分析數(shù)字

假定某個產(chǎn)品的售價是$3.50/個,當(dāng)訂購數(shù)量大于10時,就提供5%的折扣,使用 if-else語句可以計算并輸出給定數(shù)量的總價。*

  //program 3.2 Using if statements to decide on a discount

               #include  <stdio.h>

               int main ()
               {
                  const double unit_price  =  3.50;
                  int  quantity  =  0;
                  printf("Enter the number that  you want to buy :");
                  scanf("  %d ", &quantity);

                  double   total =  0.0 ;
                  if (quantity >10 )
                    total =quantity*unit_price*0.95;
                  else
                     total   = quantity*unit_price;
                  printf("The price for %d is $%.2f\n",quantity,total);
                  return  0 ;
               }

分析數(shù)字

下面用另外幾個例子練習(xí)if技巧。這個程序測試輸入的數(shù)是偶數(shù)還是奇數(shù)如果是偶數(shù),就接著測試該數(shù)字的一半是否還是偶數(shù)*

  //program 3.3 Using nested ifs to analyze numbers
  #include <stdio.h>
  #include <limits.h>

  int main (void)
  {
     long test =  0 L;

     printf("Enter an integer less than %1d:", LONG_MAX)  
     scanf(" %1d", &test );

     if (test  % 2L == 0L)
     {
         printf("The  number  %1d  is even", test);

         if((test/2l)    %  2L== 0L);
         {
            printf("\nHalf of  %1d is also even", test);
            printf("\nThat's interesting isn't it?\n");
         }
      }
     else
       printf("The number %1d is odd\n", test);
       return 0 ;
      }

將大寫字母轉(zhuǎn)化為小寫字母

這個例子使用新的邏輯運算符,將輸入的大寫字母轉(zhuǎn)化為小寫字母

          //program  3.4 converting uppercase  to lowercase
                  #include <stdio.h>
              
                  int main (void)
                  {
                     char  letter  = 0;

                     printf (”Enter an uppercase letter: ");
                     scanf("%c", &letter);

                    if (letter >= 'A ')( letter <= 'Z')
                       {
                         letter = letter - 'A' + 'a';
                         printf("You entered an uppercase %c\n", letter);
                       }
                       else
                          printf("Try using the shift key! I want a capital letter.\n");
                   return 0;
                 }

轉(zhuǎn)換字母的一種更好的方式

//program 3.5 Testing letters an easier way
#include <stdio.h>
int main (void)
{
   char  letter = 0;

   printf("Enter an upper case letter:");
   scanf(" %c ", &letter);

   if ((letter >= 'A')&&(letter <= 'z'))
   {
       letter += 'a'-'A';
       printf("You enter an uppercase %c.\n", letter);
   }
   esle 
      printf("You did not enter an uppercase letter.\n");
   return 0;
    }

**使用條件運算符 **

這個折扣業(yè)務(wù)可以轉(zhuǎn)換為一個小例子。假定產(chǎn)品的單價仍是¥3.50,但提供三個級別的折扣:數(shù)量超過50,折扣為15%;數(shù)量超過20,折扣為10%;數(shù)量超過10,折扣為5%.

//program 3.6 Multiple discount levels
#include <stdio.h>

int main (void)
{
   const double unit_price =3.5;
   const  double    discount1  = 0.05;
   const  double    discount2  = 0.1;
   const  double    discount3  =0.15
   double total_price = 0.0;
   int  quantity = 0;

    printf("Enter  the  number that you want to buy: ");
    scanf("  %d ",  &quantity);

    total_price  =quantity*unit_prine*(1.0  -
                                           (quantity > 50 ?  discount3  :  (
                                           (quantity  >20  ?  discount2  : (
                                (quantity  > 10  ? discount1   :  0.0))));
    printf("The price for %d  is $%.2f\n",quantity,total_price);
    return  0 ;
    }

清楚地使用邏輯運算符

假定程序要為一家大型藥廠面試求職者。該程序給滿足某些教育條件的求職者提供面試的機會。滿足如下條件的求職者會接到面試通知*:
(1)25歲以上,化學(xué)專業(yè)畢業(yè)生,但不是畢業(yè)于耶魯。
(2)耶魯大學(xué)化學(xué)專業(yè)畢業(yè)生。
(3)28歲以下,哈弗大學(xué)經(jīng)濟學(xué)專業(yè)畢業(yè)生。
(4)25歲以上,耶魯大學(xué)非化學(xué)專業(yè)畢業(yè)生。
實現(xiàn)該邏輯的程序如下:

 //program 3.7 confused recruiting policy
#include < stdio.h >
#include < stdbool.h >

int main ( void )
{
   int age        =  0;
   int college   =  0;
   int subject   =  0;
   bool interview  =  false;

   printf("\nWhat college? 1 for harvard, 2 for Yale, 3 for other: ");
   scanf("%d", &college);
   printf("\nwhat subject? 1 for Chemistry, 2 for economics, 3 for other: ")
   scanf("%d", &subject);
   printf("\nHow old is the applicant? ");
   scanf("%d", &age);

   if(age >25 && subject  ==  1) && (college  == 3 || college ==1 )
      interview  =   true ;
   if (college  ==  2 &&  subject   ==  1 )      邏輯與(且)
       interview =   true;
   if(college == 2 && (subject == 2 || subject == 3)  &&  age  > 25 )
        interview  = true;
    if(college == 2 &&(subject ==  2  || subject  == 3 ) &&  age > 25)
        interview  =  true;

    if(interview)
       printf("\n\nGive  'em an interview\n");
    else
       printf("\n\nReject  'em\n");
    return  0;
 }

試試看 :選擇幸運數(shù)字

這個例子假定,在抽獎活動中有三個幸運的數(shù)字,參與者要猜測一個幸運的數(shù)字,switch語句會結(jié)束這個猜測過程,給出參與者可能贏得獎勵.*

        //program 3.8 Lucky Lotteries
        #include<stdio.h>

        int  main (void)
        {
            int  choice = 0;

            printf("pick  a number between 1 and 10 and you may a prize ! ");
            scanf("%d", &choice);

            if ((choice > 10 ) || (choice < 1 ))      邏輯或
            choice =  11

            switch(choice)
           {
                case 7:
                   printf("Congratulations!\n");
                   printf("You win the collected works of Amos Gruntfutock.\n");
                   break;

               case 2:
                  printf(" You win the folding thermometer-pen-watch-umbrell.\n")
                  break;

                case 8:
                   printf("You win the  lifetime  supply of  aspirin   tablets.\n")
                   break;

               case 11:
                 printf("Try  between  1 and  10.You wasted your guess.\n")
                 break;

               default:
                 printf("Sorry, you  lose.\n");
                 break;
           }
           return 0;
       } 

試試看:是或否

//program 3.9 testing cases
#include <stdio.h>

int main(void)
{
    int main(void)
    char answer =0;
 
   printf(" Enter Y or N:  ");
   scanf(" %c", &answer);
 
switch(answer)
{
    case 'y':case 'y':
    printf("You responded in the affirmative.\n");
    break;

    case 'n': case 'N':
    printf("You responded in the negative.\n");
    break;

    default:
    printf("You did not respond correctly...\n");
    break;
  }
  return 0;
}

switch 語法的使用


#include "stdafx.h"
#include "stdio.h"
#define UP    1
#define DOWN  2
#define LEFT  3
#define RIGHT 4


int _tmain(int argc, _TCHAR* argv[])
{  
    int dir = UP;
    switch (dir){
    case UP:
        printf("GO up\n");
        break;
    case DOWN:
        printf("GO d");
        break;
    case LEFT:
        printf("Go left\n");
        break;
    case RIGHT:
        printf("Go Right\n");
        break;
    }
    
    return 0;
}


int main (void)
   {
           int a = 10;
           int b = 8;
          if(a > b){
            printf(" Max number is a, %d, a");
           }
          else{
             printf("Max number is b, %d,b");
           }
          return 0;
}
int main(void)
    {
         int  score =0;
     if(score >80){
       printf("Fine\n");
      }else if(score >60){
         printf("Ok\n");
       }esle(score<60){
          printf("Fail\n");
        return 0;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 第一部分Common Lisp介紹第1章 介紹一下Lisp你在學(xué)的時候覺得已經(jīng)明白了,寫的時候更加確信了解了,教別...
    geoeee閱讀 3,218評論 5 8
  • 現(xiàn)在看書,心里總是緊張,習(xí)慣了快速閱讀,一目幾行,以往只求了解大概意思,不求精讀,可往往到了想要好好看書的時候,老...
    carek碩閱讀 149評論 0 0
  • 文/楓丹白露 本故事純屬虛構(gòu),如有雷同,實屬巧合 ( 二 ) 鄭炳強提出為了說...
    楓丹白露_閱讀 1,670評論 0 2
  • 入選時間:2016年 7月31日 入選級別:第七層融會貫通 入選理由:i_佚名,男,90后,在校大學(xué)生,物理學(xué)專業(yè)...
    周助人閱讀 441評論 0 0

友情鏈接更多精彩內(nèi)容