【C语言初阶】分支和循环(猜数字游戏)

分支和循环

代码的本质我感觉就是循环+条件判断,这里首先总结的就是分支和循环(分支也就是选择判断)。
1.if else(或判断)
2.switch(精准打击)
3.while(先判断后循环)
4.for(符合条件后循环)
5.do while(先执行后判断)

代码格式

if()
{
    
    
 ;
}
else
switch()
{
    
    
   case 1:
       break;
   case 2:
       break;
   case 3:
   .............................. 
}
while()
{
    
    }
for(表达式;表达式;表达式3)
    循环语句;

猜数字游戏

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h>
void menu() 
{
    
        printf("**********************************\n");    printf("***********  1.play     **********\n");    printf("***********  0.exit     **********\n");    printf("**********************************\n"); }
void game() 
{
    
        int random_num = rand()%100+1;    
int input = 0;    
while(1) {
    
            
printf("请输入猜的数字>:");        
scanf("%d", &input);       
 if(input > random_num)   
 {
    
                
printf("猜大了\n");  
 }       
 else if(input < random_num)        
 {
    
    
             printf("猜小了\n");       
  } 
   else
    {
    
    
             printf("恭喜你,猜对了\n");            
                       break;        
       }    
   } 
 } 
 int main() 
{
    
        
  int input = 0;        
  srand((unsigned)time(NULL));    
   do    
   {
    
        
       menu();   
       printf("请选择>:");                
       scanf("%d", &input);        
       switch(input)        
       {
    
           
        case 1:        
            game();        
                break;    
         case 0:   
            break;          
         default:            
           printf("选择错误,请重新输入!\n");           
           break;        
           }                                   }     while(input);    
    return 0; 
    }

猜你喜欢

转载自blog.csdn.net/weixin_43762735/article/details/109356820