【发布时间】:2021-10-31 01:44:11
【问题描述】:
如果标题有误导性,我深表歉意,因为我不知道从哪里或如何开始。
最近我写了一个数学游戏,可以生成随机数并将它们转换为方程式。但是,如果我想让show-stats 之类的命令显示您的统计数据,程序所能做的就是接受数字。我必须编写命令,然后在后面输入一个数字才能让命令像这样被识别
show-stats 0
score is 1
show-stats
0 //number is required for some reason
score is 1
这是我写的一个小例子
#include <stdio.h>
#include <string.h>
int main() {
int bar;
char foo[]="";
int score = 1;
scanf("%s%i",foo,&bar);
if(strcmp(foo,"show-stats"))
{
printf("Score is %i",score);
}
if(bar == 2)
{
score = bar*2;
printf("Doubled Points.\n");
}
}
这是实际代码,以备不时之需。另外,我想要关于实际代码的顾问,比如它的意大利面或某些东西是否消耗性能,或者如果它不是太麻烦的话,我一般可以改进什么。在此先感谢,我愿意接受建议。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define VER 10
#define DIV "-----"
int main()
{
system("clear");
unsigned int x,y; //equation numbers
int ans,sum; //user answer
unsigned int max = 10; //max possible number that can be made, cannot go under 10.
int score; //what do you think?
char operation;
int correctAnswers = 0,wrongAnswers = 0;
printf("Math game\nVersion %i.\n",VER);
for (; ;)
{
//phase 1; make numbers.
srand(time(NULL));
x = rand() % max;
y = rand() % max;
//phase 2; make operation type.
operation = rand() % 2;
switch (operation)
{
case 0:operation = '+';sum = x + y;break;
case 1:operation = '-';sum = x - y;break;
}
//phase 3; write question to console and get user answer
printf("What is %i %c %i? ",x,operation,y); //get input
scanf("%i",&ans);
//phase 4; determine right answer
if (ans == sum)
{
score++;
correctAnswers++;
max++;
printf("Your correct! +1!\n");
printf("%sStats%s\nScore:%i\nMax possible number:%i\nCorrect Answers:%i\nWrong Answers:%i\n%s%s%s\n",DIV,DIV,score,max,correctAnswers,wrongAnswers,DIV,DIV,DIV); //print stats when user wins,is a seperate call for readability. same thing on line 53 but for loss
}
else
{
score--;
wrongAnswers++;
if(max>10){max--;}; //assures max doesn't go under 10
printf("Wrong! -1\n");
printf("%sStats%s\nThe correct answer was %i\nMax possible number : %i\nScore : %i\nCorrect Answers : %i\nWrong Answers : %i\n%s%s%s\n",DIV,DIV,sum,max,score,correctAnswers,wrongAnswers,DIV,DIV,DIV);
}
}
}
【问题讨论】:
-
第一件事,从不使用
scanf()读取用户输入而不检查返回值。一般建议是使用fgets()读取完整的输入行,然后使用更丰富(且不易出错)的库进行解析,例如strtol(). -
char foo[]="";你觉得用scanf读取字符串时这个数组能容纳多少个字符?提示:不能! -
@cs07 你知道什么是函数,什么是函数返回值吗?
-
您的最小示例与您的实际代码有何关系?您没有在第二个 sn-p 中读取任何字符串。
-
阅读 scanf 的手册页是个好主意