一、减少不必要的全局变量
1、指针代替全局变量
示例代码:
#include <stdio.h>
#include <conio.h>
int score = 5;
void addScore() {
score = score + 1;
}
void minusScore() {
score = score - 1;
}
void printScore() {
printf("%d\n",score);
}
int main() {
addScore();
printScore();
minusScore();
printScore();
addScore();
printScore();
minusScore();
printScore();
return 0;
}
运行结果:
指针:
#include <stdio.h>
#include <conio.h>
void addScore(int *temp) {
*temp = *temp + 1;
}
void minusScore(int *temp) {
*temp = *temp - 1;
}
void printScore(int sc) {
printf("%d\n",sc);
}
int main() {
int score = 5;
addScore(&score);
printScore(score);
minusScore(&score);
printScore(score);
addScore(&score);
printScore(score);
minusScore(&score);
printScore(score);
return 0;
}
运行结果:
二、int sprintf(char *string, char *farmat [,argument,...]);
函数名: sprintf
功 能: 送格式化输出到字符串中
用 法: int sprintf(char *string, char *farmat [,argument,...]);
程序例:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define PI 3.1415
int main() {
char buffer[80];
int a;
a=sprintf(buffer, "An approximation of Pi is %f\n", PI);
puts(buffer);
printf("返回值a=%d\t输出buffer中字符串的长度strlen(buffer)=%d\n",a,strlen(buffer));
return 0;
}
运行结果:
三、音乐播放函数的封装
每播放一次音乐需要三行语句,播放不同音乐需要多次修改文件名及相应名称!
mciSendString(_T("close jpmusic"),NULL,O,NULL); //先把前面一次的音乐关掉
mciSendString(_T("open D:\\Jump.mp3 alias jpmusic"), NULL, O, NULL); //打开音乐
mciSendString(_T("play jpmusic"), NULL, O, NULL); //仅播放一次
进行封装如下:
#include <graphics.h>
#include <conio.h>
#include <string.h>
#pragma comment(lib,"Winmm.lib")
void PlayMusicOnce(char *fileName) {
char cmdString1[50] = "open ";
strcat(cmdString1,fileName);
strcat(cmdString1," alias tmpmusic");
mciSendString(_T("close tmpmusic"), NULL, O, NULL); //先把前面一次的音乐关掉
mciSendString(_T(cmdString1), NULL, O, NULL); //打开音乐
mciSendString(_T("play tmpmusic"), NULL, O, NULL); //仅播放一次
}
int main() {
initgraph(640,480);
while (1) {
PlayMusicOnce("D:\\jump.mp3");
Sleep(2000);
PlayMusicOnce("D:\\f_gun.mp3");
Sleep(2000);
}
_getch();
closegraph();
return 0;
}
四、