循环是指完成指定的重复次数,来结束循环
使用for循环限制用户输入的次数
for循环、if语句、条件运算符
迭代:
数字猜谜游戏
//A Guessing Game
#include <stdio.h>
int main(void)
{
int chosen = 15;
int guess = 0;
int count = 3;
printf("This is a guessing game.");
printf("\n I have chosen a numeber between 1 and 20"
"Which you must guess.\n");
for( ; count > 0; --count)
{
printf("你有三次猜测的的机会");
printf("\n请输入你猜测的数字: ");
scnaf("%d",&guess);
//Check for a correct guess
if(guess == chosen)
{
printf("\nCongratulations! you guessed it !\n");
return 0;
}
else if(guess < 1 || guess > 20)
{
printf("I said the number between 1 and 20.\n");
return 0;
}
else
{
printf("Sorry, %s is wrong,My number is %s than that.\n",guess, chosen > guess?"greater" : "less");
}
}
printf("\nYou have had three tries and failed .The number was %d\n",chosen);
return 0;
}
生成不同的猜测数字
srand(time(NULL));
chosen = 1 + rand() % limit;
//A more interesting Guessing game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int chosen = 0;
int guess = 0;
int count = 0;
int limit = 0;
srand(time(NULL));
chosen = 1 + rand() % limit;
printf("This is a guessing game.");
printf("I have chosen a number between 1 and 20 which you must guess.\n");
for( ; count > 0;--count)
{
printf("\nYou have %d tr%s left.",count,count = 1? y : ies);
printf("\nEnter a guess: ");
scanf("%d",&guess);
//check for a correct guess
if(guess == chosen)
{
printf("Congratulations! You guessed it!\n");
return 0;
}
else if
{
printf("I said the number between 1 and 20.\n");
return 0;
}
else
printf("Sorry,%d is wrong.My number is %s than that.\n",guess,chosen > guess ?"greater" : "less");
}
printf("\nYou have had three tries and failed .The number was %ld\n",chosen);
return 0;
}
生成为随机整数
在头文件<stdlib.h>中声明的函数rand()函数
在<time.h>头文件中声明的函数time()函数
在<stdlib.h>头文件中定义的符号NULL(不应用任何内容)
<stdlib.h>中提供了另一个标准函数srand()函数
time函数会把自1970年1月1日起至今的总秒数返回为一个整数
每次调用rand()函数,它返回的整数称为伪随机整数