C语言入门经典

第三章条件判断程序

2016-04-14  本文已影响123人  全無

今年是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语言中的三目运算符:“?:”,其格式为:
** 表达式1 ? 表达式2 : 表达式3;**

检查条件

这个程序让用户输入一个1~10之间的数字,再确定该数字有多大。

 //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语句分析数字

假定某个产品的售价是$3.50/个,当订购数量大于10时,就提供5%的折扣,使用 if-else语句可以计算并输出给定数量的总价。*

  //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 ;
               }

分析数字

下面用另外几个例子练习if技巧。这个程序测试输入的数是偶数还是奇数如果是偶数,就接着测试该数字的一半是否还是偶数*

  //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 ;
      }

将大写字母转化为小写字母

这个例子使用新的逻辑运算符,将输入的大写字母转化为小写字母

          //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;
                 }

转换字母的一种更好的方式

//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;
    }

**使用条件运算符 **

这个折扣业务可以转换为一个小例子。假定产品的单价仍是¥3.50,但提供三个级别的折扣:数量超过50,折扣为15%;数量超过20,折扣为10%;数量超过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岁以上,化学专业毕业生,但不是毕业于耶鲁。
(2)耶鲁大学化学专业毕业生。
(3)28岁以下,哈弗大学经济学专业毕业生。
(4)25岁以上,耶鲁大学非化学专业毕业生。
实现该逻辑的程序如下:

 //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;
 }

试试看 :选择幸运数字

这个例子假定,在抽奖活动中有三个幸运的数字,参与者要猜测一个幸运的数字,switch语句会结束这个猜测过程,给出参与者可能赢得奖励.*

        //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;
    }
上一篇下一篇

猜你喜欢

热点阅读