【问题标题】:Cant get correct output of one line无法正确输出一行
【发布时间】:2012-11-07 23:49:54
【问题描述】:

我制作了这个程序,它可以生成两个骰子的掷骰数,然后将它们相加,然后显示它尝试了多少次。我的问题是程序将它们全部正确添加,它似乎无法打印成功达到您在开始时输入的总数所需的尝试次数。我想要的预期输出示例如下。

  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' );

      }

【问题讨论】:

    标签: c printf output


    【解决方案1】:

    我认为你应该改变这个条件if (SUM == i)如下:

        if (SUM == input)
    

    因为您想将SUMinput 进行比较。

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 2021-12-10
      • 1970-01-01
      相关资源
      最近更新 更多