编辑:非常感谢大家的评论!在你们的指导下,我成功修复了胜率和数组数字出现异常的问题。但是,我还没有修复赢或输需要的平均投注次数。我已经更新了我的代码,如下所示。
开始原始帖子:
预先感谢任何阅读此帖并提供建议的人!
所以,我正在为编程课程做一个典型的赌博游戏,直到你赢了或输光为止。代码运行良好,但当我添加正反面部分时,存储投注次数的数组就会出现问题。当我用注释隐藏实际的抛硬币部分时,数组就能正常工作。当我运行它与抛硬币时,betArray存储的数字就变得非常奇怪(负整数、十亿级整数)。
以下是目前的代码:
#include<stdio.h>
#include<stdlib.h> /*Enables use of rand()*/
int main () {
setvbuf(stdout, NULL, _IONBF, 0); /*Allow me to use repl.it*/
/*Enter Gambler's name*/
char gambleName[15] = "";
printf("Enter gambler's name:\n");
scanf("%s", gambleName);
printf("\nWelcome, ");
printf("%s! \n", gambleName);
/*Enter Stakes*/
int availableFunds;
int goalFunds;
printf("We'll be betting $1 per bet. Enter your available funds:\n");
scanf("%d", &availableFunds); /* Saves stakes as availableFunds */
int seedVal=4;
srand(seedVal);
/*Butter the gamblers up*/
if(availableFunds>=1) {
printf("%d? Wow, %s - that's a great start!\n",availableFunds, gambleName);
/*Enter Goal*/
printf("How much do you want to win today? Enter a value up to 10000 with no commas, decimals or spaces:\n"); /*Saves goal as goalFunds*/
scanf("%d",&goalFunds);
/*Recognize ambitious gamblers*/
if (goalFunds > 10*availableFunds) {
printf("Wow, ambitious! Let's get started.\n");
}
else {
printf("OK, let's get started!\n");
}
printf("\n");
/*begin gambling problem*/
int betArray[1000]={0};
int game = 0;
int bet=0;
float wins = 0;
int losses = 0;
for (game=0 ; game<1000; game++) {
if (availableFunds>0 && availableFunds<goalFunds) {
int toss = rand()%2;
bet+=1;
/*losing bet*/
if (toss == 0) {
availableFunds -= 1;
losses += 1;
}
/*winning bet*/
else {
availableFunds += 1;
wins += 1;
}
betArray[game+1] = bet;
}
else {
break;
}
}
int sumBet = 0;
for (game=0;game<1000;game++) {
sumBet+=betArray[game];
}
float betAverage = sumBet/1000;
float winOutOfGames = wins/1000;
float winPercent = winOutOfGames*100;
/*print totals*/
printf("%d games played with:\n",game);
printf("%.f goals reached\n",wins);
printf("%d down-and-out losses.\n",losses);
printf("You won ~%.1f%% of your games.\n",winPercent);
printf("On average, it took you %.f bets to win or go broke.\n",betAverage);
printf("\n");
printf("Thanks for playing!\n");
for (game = 1; game <= 50; game++) {
printf("Bets in game [%d] = %d\n",game,betArray[game]);
}
}
/* Send the broke guys packing*/
else {
printf("$%d...? You may need to stop at an ATM... ¯\\_(ツ)_/¯ See you next time!\n", availableFunds);
}
return 0;
}
抱歉代码有些混乱,我添加了一些内容并想要发送最新版本。谢谢!
if (availableFunds>0 && availableFunds<goalFunds) {
块中,你从未对betArray[game]
进行任何赋值,因此你的大部分数组都是无用的。 - M.MbetArray[game]
(即从else if
中删除)移到了if (availableFunds>0 && availableFunds<goalFunds) {
块中,根据 M.M 的建议。这是完整代码的链接:https://repl.it/Do5j/2 - Kevin W.int winRatio = wins/game;
将为零。 这些值都是整数。 您需要将wins
或game
中的至少一个强制转换为浮点类型,并且winRatio
也应该是浮点类型。 您可能需要在else if (availableFunds == 0 || availableFunds >= goalFunds) { }
中使用break;
,我认为您应该省略if
条件; 它只是与之前“如果可以赌博”的条件相比的“否则”子句。 - Jonathan Leffler