猜数游戏(多文件编程)

单个文件内实现的话无疑是很简单的
作为我首个多文件编程的项目,纪念一波
盛况
关键点在于.c文件要先全部加入到当前项目中,编译器会按照项目文件的指引把各个.c文件分别编译为同名的.obj目标文件,然后再将这些.obj目标文件链接到一起,生成最后的.exe可执行文件。
顺便吐槽一句:用vim搞多文件项目好麻烦
vim多文件编程教程在此

各文件内容
main.c

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "guess.h"
int main(void)
{
	int number;
	char reply;
	srand(time(NULL));
	do{
		number = MakeNumber();
		GuessNumber(number);
		printf("Do you want to continue(Y/N or y/n)?");
		scanf(" %c", &reply);
		while(reply != 'y' && reply != 'n' && reply != 'Y' && reply != 'N')
            scanf(" %c", &reply);
	}while(reply == 'y' || reply =='Y');
	return 0;
}

MakeNumber.c

#include <stdio.h>
#include <assert.h>
#include "MakeNumber.h"
//函数功能:生成一个随机数
//函数参数:无
//函数返回值:生成的随机数
int MakeNumber(void)
{
	int number;
	number = (rand() % (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER;
	assert(number >= MIN_NUMBER && number <= MAX_NUMBER);
	return number;
}

GuessNumber.c

#include <stdio.h>
#include "IsRight.h"
#include "IsValidNum.h"
//函数功能:用户猜数字
//函数参数:number为计算机生成的数
//函数返回值:无
void GuessNumber(int number)
{
	int guess, count = 0, right = 0, ret;
	do{
		printf("Try %d:", count+1);
		ret = scanf("%d", &guess);
		while(ret != 1 || !IsValidNum(guess))
		{
			printf("Input error!\n");
			while(getchar() != '\n');
			printf("Try %d:", count+1);
			ret = scanf("%d", &guess);
		}
		++count;
		right = IsRight(number, guess);
	}while(!right && count < MAX_TIMES);
	if(right)
		puts("Congratulations! You\'re so cool!");
	else	printf("Mission failed after %d attempts.\n", MAX_TIMES);
	return ;
}

IsValidNum.c

#include "IsValidNum.h"
int IsValidNum(int number)
{return number >= MIN_NUMBER && number <= MAX_NUMBER;}

IsRight.c

#include <stdio.h>
#include "IsRight.h"
//函数功能:比较guess和number大小,
//函数参数:number为被猜数,guess为用户给出的数
//函数返回值:正确为1
int IsRight(int number, const int guess)
{
	if(guess == number)return 1;
	if(guess < number)
		puts("Wrong! Too small!");
	if(guess > number)
		puts("Wrong! Too big!");
	return 0;
}

自定义头文件
guess.h

int MakeNumber(void);
void GuessNumber(int number);
int IsValidNum(int number);
int IsRight(int number, int guess);

GuessNumber.h

void GuessNumber(const int number);

MakeNumber.h

#define MAX_NUMBER 100
#define MIN_NUMBER 1
int MakeNumber(void);

IsRight.h

#define MAX_TIMES 10
int IsRight(int number, int guess);

IsValidNum.h

#define MAX_NUMBER 100
#define MIN_NUMBER 1
int IsValidNum(int number);
posted @ 2020-11-17 20:14  快乐永恒  阅读(392)  评论(1编辑  收藏  举报