简体   繁体   English

如何在 C 编程中的 if else 语句中使用循环

[英]How to use loop in an if else statement in C Programming

I need to construct an algorithm that reads the membership type and item price.我需要构建一个读取会员类型和商品价格的算法。 The output will be the amount to pay after discount.输出将是折扣后支付的金额。 The program allows both lowercase and uppercase character input and will prompt user to reenter membership type if code entered is invalid.该程序允许输入小写和大写字符,如果输入的代码无效,将提示用户重新输入会员类型。

The membership works as following: Platinum - P - 30% Gold - G - 20% Silver - S - 10% Non-member - X - 0%会员资格如下: 白金 - P - 30% 黄金 - G - 20% 银 - S - 10% 非会员 - X - 0%

I manages to get an output when the membership is inserted correctly (P,G,S or X).当正确插入成员资格(P、G、S 或 X)时,我设法获得输出。 However when a wrong character is inserted, I am not sure how to repeat the program until I get the correct output...但是,当插入错误的字符时,我不确定如何重复该程序,直到获得正确的输出...



int main()
{
   
    
    printf("Suria Supermarket");
    
    char membershipType;
    char membershipTypeTwo;
    float itemPrice;
    
    
    char membershipType2;
    float itemPrice2;
    
    printf("\nEnter membership type (S or G or P, X for non-member): %c", membershipType);
    scanf("%c", &membershipType);
    
    printf("Enter item price (RM): ",itemPrice); 
    scanf("%f",&itemPrice);
    
    
   float discountedAmount;
   float discountedAmount2;
       
    if(membershipType=='s') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 10\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.1));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
        
    }
    else if(membershipType=='S') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 10\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.1));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
        
    } 
    else if(membershipType=='g') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 20");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.2));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='G') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 20");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.2));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='p') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 30");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.3));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='P') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 30");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.3));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='x'){
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 0");
        printf("\n");      
        printf("Discounted Price: RM %1.2f", itemPrice);
    }
        else if(membershipType=='X') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 0");
        printf("\n");      
        printf("Discounted Price: RM %1.2f", itemPrice);
    }
    else {
        printf("Invalid code, please enter again.");
        printf("\n");
        printf("\n");
        if(membershipTypeTwo!='s','S','g','G','p','P','x','X');
        
        printf("Enter membership type (S or G or P, X for non-member): %c",membershipTypeTwo);
        scanf("%c%*c",&membershipTypeTwo);
        printf("Enter item price (RM): ",itemPrice); 
        scanf("%f",&itemPrice);
        
            
}

       return 0;

}```

Instead of large if-else ladders use switch statement使用switch语句代替大型 if-else 阶梯

switch(toupper((unsigned char)membershipType))
{
    case 'P':
    /* ... */
    break;
    case 'G':
    /* ... */
    break;
    default:
        print("Wrong membership type\n");
    break;
}

Write a loop to read the input value, exiting only when there's a match or an error condition on the input stream.编写一个循环来读取输入值,仅在输入流上存在匹配或错误条件时退出。

As a bit of a labor-saver, you can put all the valid membership types into a string like "PGSX" and use the strchr library function to see if the entered value is part of the string, rather than explicitly checking against each possible character.为了节省一点劳力,您可以将所有有效的成员资格类型放入像"PGSX"这样的字符串中,并使用strchr库函数来查看输入的值是否是字符串的一部分,而不是显式检查每个可能的字符. You can also use the toupper or tolower functions to convert the input to one of the other case for comparisons.您还可以使用touppertolower函数将输入转换为另一种情况以进行比较。

/**
 * These headers are necessary for the code below.
 */
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
...
/**
 * Create a flag to tell us if we need to keep scanning
 * for input.
 */
bool done = false;
...
while ( !done )
{
  /**
   * Stores the number of items read from scanf.
   */
  int itemsRead;

  /**
   * Create a string with the valid input characters.
   */
  const char *membershipTypeList = "PGSX";

  printf( "\nEnter membership type..." );
  /**
   * The leading blank in the " %c" format string
   * tells scanf to skip over any leading whitespace
   * so you don't accidentally pick up a newline from
   * a previous entry.
   *
   * scanf returns the number of items successfully
   * read and assigned, or EOF on end-of-file or 
   * error.  A return value of 1 means we read *something*;
   * we then compare that against the values in the 
   * membershipTypeList string.  If strchr returns
   * NULL, the the character wasn't in the string
   * and we prompt the user to try again.  A return 
   * value of 0 means we had a matching failure, 
   * which almost never happens with %c because 
   * it will match any printing character.  A
   * return value of EOF means scanf either saw
   * and end of file condition or an error on
   * the input stream.
   */
  if ( (itemsRead = scanf( " %c", &membershipType )) == 1 )
  {
    /**
     * You can assign the result of a comparison
     * to an int or boolean variable.  If this
     * looks too weird for you, you can replace 
     * it with:
     *
     *    if ( strchr(...) != NULL )
     *      done = true;
     */
    done = strchr( membershipTypeList, 
      toupper( membershipType ) ) != NULL;

    if ( !done )
       printf( "\nThat wasn't a valid membership type, try again..." );
  }
  else if ( itemsRead == 0 )
  {
    printf( "\nMatching failure on input, try again..." );
  }
  else
  {
    done = true;
  }
}
/**
 * Check to see if we exited the loop because
 * a problem with the stream
 */
if ( feof( stdin ) || ferror( stdin ) )
{
  fprintf( stderr, "Error on input stream, exiting...\n" );
  exit( -1 );
}

/**
 * Process membershipType as normal
 */

Welcome to handling interactive input in C. It's usually a pain in the butt.欢迎使用 C 语言处理交互式输入。这通常让人头疼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM