【发布时间】:2014-10-04 23:08:58
【问题描述】:
我正在用 c 语言制作一个简单的游戏,但在从函数 t 传递和接收信息时遇到问题。
我希望代码基本上运行 t 函数,然后打印结果分数。然后,除非其中一个分数大于 3 并且比另一个分数高 2,否则我希望它再次运行 t 并打印结果。
现在它正在运行一次 t 函数然后卡住了。
任何帮助或想法将不胜感激,或者如果我遗漏了信息,请发表评论。
#include <stdio.h>
#include <stdlib.h>
void t(int *score1,int *score2)
{
int r,p;
r=rand() % 140;
if(r>30)
{
*score1=score1+1;
}
if(30>r)
{
*score2=score2+1;
}
if(r==30)
{
*score2=score2+1;
}
}
void main(int argc, char *argv[])
{
srand(time(NULL));
int score1 =0;
int score2 =0;
int x =0;
while(x==0)
{
t(&score1, &score2);
printf("%d\n",score1);
printf("%d\n",score2);
if(score1 > 3 && score1==score2+2)
{
printf("Player 1 Wins\n");
x++;
}
if(score2 > 3 && (score2==score1+2))
{
printf("Player 2 Wins\n");
x++;
}
}
return;
}
【问题讨论】:
-
atoi()解析const char *,而不是int *。它旨在解析 ascii 代码数字。你也不需要多次运行srand(time(NULL))。将其移至 while 循环的上一行。 -
我改变了你说的。我只是没有得到 score1 和 score2 的任何好的值。他们创造了奇怪的价值观。我做错了什么?
-
如果你学会了正确缩进和格式化你的代码,它会让循环问题更容易追踪。你可以在这里试试。
-
void t(){...} 中的
score1和score2是一个指针,它的值通常是一个内存地址。所以你必须把它改成*score1=*score1+1或者*score+=1
标签: c function while-loop