我制作了这个程序,它可以生成两个骰子的掷骰子,然后将它们相加,然后显示它尝试了多少次。我的问题是程序将它们全部正确添加,它似乎无法打印成功达到您在开始时输入的总数所需的尝试次数。我想要的预期输出示例如下。
Dice Thrower
============
Total sought : 7
Result of throw 1 : 4 + 4
Result of throw 2 : 1 + 4
Result of throw 3 : 2 + 6
Result of throw 4 : 1 + 1
Result of throw 5 : 4 + 3
You got your total in 5 throws!
这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int validator(); //Function to validate
void clear(void); //Clear function
int main() {
int i=0,counter = 0, input, SUM, random1, random2; //Variables
printf("Dice Thrower\n"); //Print statements
printf("============\n");
printf("Total sought : ");
input = validator(); //Call Function Validator
srand(time(NULL));
for (i = 2; SUM!= input; i++) //For Loop for random dice throws
{
random1 = rand()%6+1;
random2 = rand()%6+1;
SUM = random1 + random2;
counter++;
printf("Result of throw %d : %d + %d\n", counter, random1, random2);
if (SUM == i)
{
printf("You got your total in %d throws!\n", counter); //Print statement for final total
}
}
return 0;
}
int validator() //Validator function
{
int tries = 1, boss, returnvalue;
char k;
do{
boss = scanf("%d%c", &returnvalue,&k);
if (boss == 0)
{
printf ("Invalid input, Try again : ");
clear();
}
else if(returnvalue >= 13 || returnvalue <= 1)
{
printf("Invalid integer entered, please enter an integer greater than or equal to 2 and less than or equal to 12 : ");
}
else if(k != '\n')
{
printf("Trailing characters present, reenter : ");
clear();
}
else
{
tries = 0;
}
} while ( tries == 1);
return returnvalue;
}
void clear (void) { //Clear function
while ( getchar() != '\n' );
}