簡體   English   中英

輸入y時,循環將跳過宏while循環

[英]The loop will skip the macro do while loop when y is entered

我需要有關此的幫助...我的c語言中的問題是當我執行此程序時,當我要重復滾動時,第二次以后將不顯示滾動...我該怎么辦? 我不知道該怎么辦才能解決此問題。

#include <stdio.h>
#include <stdlib.h>
int main()
{
  int i, a, n, z;
  char player[5][150], b, c;
  float ave, total, f1, f2, f3;

  total = 0;
  ave = 0;
  printf("\nPlease enter number of players : ");
  scanf("%d", &a);

  for (i = 0; i < a; i++)
  {
    printf("\nEnter player %d's name : ", i + 1);
    scanf("%s", &player[i][150]);
  }

  printf("\nChoose the amount of dice used : ");
  scanf(" %d", &n);

  do
  {
    for (z = 1; z <= a; z++)
    {
      printf("\n\t%s\n ", player[z]);

      if (n == 1)
      {
        do
        {
          f1 = 1.0 + 6.0 * ((float) rand() / RAND_MAX);
          printf("\nRoll : %.0f\n", f1);
          total = f1;
          printf("Total : %.0f\n", total);
        }while (f1 == 6);
      }
      else if (n == 2)
      {
        do
        {
          f1 = 1 + (rand() % 6);
          f2 = 1 + (rand() % 6);
          printf("\nRoll : %.0f,%.0f\n", f1, f2);
          total = f1 + f2;
          printf("Total : %.0f\n", total);
        }while (f1 == f2);
      }
      else if (n == 3)
      {
        do
        {
          f1 = 1 + (rand() % 6);
          f2 = 1 + (rand() % 6);
          f3 = 1 + (rand() % 6);
          printf("\nRoll : %.0f,%.0f,%.0f\n", f1, f2, f3);
          total = f1 + f2 + f3;
          printf("Total : %.0f\n", total);
        }while (f1 == f2 && f2 == f3);
      }
    }
    printf("\nRoll again ? (y/n) = ");
    scanf("%s", &b);
  }while (b == 'y');
  printf("\n");

  ave = total / n;
  printf("Average : %.2f\n\n", ave);

  return 0;
}

第一件事是

scanf("%s", &b);

應該

scanf("%c", &b);

而且你必須刷新你的標准輸入你do while工作。

while ((c = getchar()) != '\n' && c != EOF);

沖洗stdin的便攜式方法

%s讀取一個C字符串,它是一個以null結尾的char數組。 包含'y'的最短字符串是2個字符的數組: "y"{ 'y', '\\0'}

所以你應該改變char b; char b[2]; ,並以這種方式使用:

    scanf("%1s", b);
}while (*b == 'y');

您當前的代碼在字符b調用未定義的行為之后(至少)寫了一個null:在那之后可能發生任何事情。 但是scanf("%1s", b); 僅讀取b[0]第一個非空白字符,並在b[1]放置null:正確。

但是恕我直言,切勿將忽略空格(空格,制表符,行尾)( %d%s%f... )的輸入與明確處理它們的輸入( %cfgets )混合使用,除非您確定為什么要這樣做。 因此,我不建議您使用scanf("%c", b);

關於這條線:

scanf("%s", &b);

變量“ b”是一個字符,因此必須將其作為字符讀取。

scanf(" %c", &b );  

注意:格式字符串中的前導空格,因此前導空格將被跳過

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM