2016-02-23 146 views
1

目标是根据统一编号为不同玩家分配平均值。问题在于它不断跳过第二个printf,并且switch语句中的字符不起作用。我敢肯定,这是我的一个非常简单的错误,但我似乎无法找到它。遇到了嵌套的循环问题

int main(){ 
float ab; 
float hits; 
int un; 
char pa; 
printf("Please enter the player number, or -1 to exit. \n"); 
scanf("%d%*c \n", &un); 
while(un!= -1) 
{ 
    printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n"); 
    scanf("%c%*c", &pa); 
    while(pa != 'E') 
    { 
      switch (pa) 
      { 
      case 'h': 
      case 'H': 
       ab += 1; 
       hits +=1; 
       break; 

      case 'o': 
      case 'O': 
       ab+=1; 
       break; 

      default: 
       printf("Error: Please insert an O or H \n"); 
       break; 
      } 
     float average = (ab/hits); 
     printf("Player %d's score is equal to: %d \n", un, average); 

     printf("Please enter the player number, or -1 to exit. \n"); 

     scanf("%d%*c \n", &un); 
    } 

} 
return 0; 
} 
+0

使用未初始化变量的值'ab'和'hits',它具有自动存储时间,调用*未定义行为*。 – MikeCAT

+0

在'printf()'中,将类型为“float”的'average'传递给'%d',调用类型为int的数据,也会调用未定义的行为。 – MikeCAT

+0

你确定第二个'printf()'被跳过吗? (由于未定义的行为,可能会跳过)是不是因为第一个'scanf()正在等待非空白字符而尚未调用? – MikeCAT

回答

0

你的循环嵌套是不完全正确,你scanf通话将挂起,您需要预初始化abhits,并最终printf有一个不正确的格式。

下面是更正后的代码[请原谅无偿风格清理]:

#include <stdio.h> 

int 
main() 
{ 
    float ab; 
    float hits; 
    int un; 
    char pa; 

    while (1) { 
     printf("Please enter the player number, or -1 to exit.\n"); 
#if 0 
     scanf("%d%*c \n", &un); 
#else 
     scanf(" %d", &un); 
#endif 
     if (un == -1) 
      break; 

     ab = 0; 
     hits = 0; 

     printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n"); 
     while (1) { 
#if 0 
      scanf("%c%*c", &pa); 
#else 
      scanf(" %c", &pa); 
#endif 
      if ((pa == 'E') || (pa == 'e')) 
       break; 

      switch (pa) { 
      case 'h': 
      case 'H': 
       ab += 1; 
       hits += 1; 
       break; 

      case 'o': 
      case 'O': 
       ab += 1; 
       break; 

      default: 
       printf("Error: Please insert an O or H\n"); 
       break; 
      } 
     } 

     float average = (ab/hits); 

#if 0 
     printf("Player %d's score is equal to: %d\n", un, average); 
#else 
     printf("Player %d's score is equal to: %g\n", un, average); 
#endif 
    } 

    return 0; 
}