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

发布于 2025-02-13 05:23:59 字数 4245 浏览 2 评论 0原文

我需要构建一种读取会员类型和项目价格的算法。 输出将是折扣后支付的金额。 该程序允许小写和大写字符输入,如果输入的代码无效,将提示用户重新进入会员类型。

会员人数如下: 铂 - p -30% 黄金-G -20% 银 - S- 10% 当正确插入会员时,非会员-x -0%

I设法获得输出(P,G,S或X)。但是,当插入错误的字符时,我不确定如何重复该程序,直到获得正确的输出为止...



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;

}```

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%

I manages to get an output when the membership is inserted correctly (P,G,S or 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;

}```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷情 2025-02-20 05:24:00

而不是大的if-else梯子使用switch语句

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

Instead of large if-else ladders use switch statement

switch(toupper((unsigned char)membershipType))
{
    case 'P':
    /* ... */
    break;
    case 'G':
    /* ... */
    break;
    default:
        print("Wrong membership type\n");
    break;
}
女中豪杰 2025-02-20 05:24:00

编写一个循环以读取输入值,仅在输入流上有匹配或错误条件时退出。

作为劳动力减少的一点,您可以将所有有效的成员资格类型放入“ PGSX”之类的字符串中是字符串的一部分,而不是明确检查每个可能的字符。您还可以使用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
 */

欢迎处理C中的交互式输入。通常,屁股很痛苦。

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. You can also use the toupper or tolower functions to convert the input to one of the other case for comparisons.

/**
 * 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文