简体   繁体   English

if语句成功后如何停止? C程序设计

[英]How to stop after successful if statement? C programming

I'm trying to get user input to find out deductions from salary and so they put their ID and a salary that is in range with that ID number. 我正在尝试获取用户输入,以找出从薪水中扣除的款项,因此他们将其ID和薪水与该ID号在一定范围内。 For example if I input ID 1 and then a salary of 500 and it should output the salary entered, salary deducted, and net salary. 例如,如果我输入ID 1,然后输入薪水500,它应该输出输入的薪水,扣除的薪水和净薪水。 It does all of that, but where it checks if the salary is in range for the correct ID number it checks it with every ID number even after the ID entered has been checked. 它会执行所有这些操作,但是在检查薪水是否在正确ID号范围内的情况下,即使检查了输入的ID后,也会使用每个ID号对其进行检查。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ID;  // variable for ID
    float Base_Salary; // variable for base salary
    float Amount_Deducted; // variable for amount deducted from employee
    float Net_Salary; // variable for employees' net salary

    printf("%s", "Enter ID: \n"); // prompt for ID number
    scanf("%d", &ID );

    // Validate user's ID
    if (ID == 1)
        printf("You have entered the ID 1\n");
    else { if (ID == 2)
            printf("You have entered the ID 2\n");
            else { if (ID == 3)
                printf("You have entered the ID 3\n");
                    else { if (ID == 4)
                        printf("You have entered the ID 4\n");
                            else { if (ID == 5)
                                printf("You have entered the ID 5\n");
                                    else { if (ID < 1 && ID > 5)
                                        printf("You didn't enter a proper ID\n");
                                    }
                            }
                    }
            }
    }

    printf("%s", "Enter your salary in the appropriate range: \n");
    scanf("%f",&Base_Salary);

    // Validations

       if (ID == 1 && Base_Salary >= 100 && Base_Salary <= 1000) {
            printf("Base salary is in range for ID given.\n");
       }
       else {
            printf("Salary must be between 100-1000 for ID 1.\n");
       }

       if (ID == 2 && Base_Salary >= 1001 && Base_Salary <= 5000) {
            printf("Base salary is in range for ID given.\n");
       }
       else {
            printf("Salary must be between 1001-5000 for ID 2.\n");
       }

       if (ID == 3 && Base_Salary >= 5001 && Base_Salary <= 10,000) {
            printf("Base salary is in range for ID given.\n");
       }
       else {
            printf("Salary must be between 5001-10,000 for ID 3.\n");
       }

       if (ID == 4 && Base_Salary >= 10,001 && Base_Salary <= 15,000) {
            printf("Base salary is in range for ID given.\n");
       }
       else {
            printf("Salary must be between 10,001-15,000 for ID 4.\n");
       }

       if (ID == 5 && Base_Salary >= 15,001 && Base_Salary <= 20,000) {
            printf("Base salary is in range for ID given.\n");
       }
       else {
            printf("Salary must be between 15,001-20,000 for ID 5.\n");
       }

    // Calculations
    if (ID == 1) {
        Amount_Deducted = Base_Salary * 0.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }
    if (ID == 2) {
        Amount_Deducted = Base_Salary * 1.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }

    if (ID == 3) {
        Amount_Deducted = Base_Salary * 2.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }

    if (ID == 4) {
        Amount_Deducted = Base_Salary * 3.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }

    if (ID == 5) {
        Amount_Deducted = Base_Salary * 4.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }

}

It really looks like switch-case is more appropriate than if-else : 看起来, switch-caseif-else更合适:

// Validate user's ID
switch (ID)
{
case 1: 
    printf("You have entered the ID 1\n");
    if (Base_Salary >= 100 && Base_Salary <= 1000)
    {
        printf("Base salary is in range for ID given.\n");
    }
    Amount_Deducted = Base_Salary * 0.50;
    Net_Salary = Base_Salary - Amount_Deducted;
    break;

case 2:
    printf("You have entered the ID 2\n");
    /* Base Salary & Amount Deducted, code here. */
    break;

case 3:
    printf("You have entered the ID 3\n");
    /* Base Salary & Amount Deducted, code here. */
    break;

case 4:
    printf("You have entered the ID 4\n");
    /* Base Salary & Amount Deducted, code here. */
    break;

case 5:
    printf("You have entered the ID 5\n");
    /* Base Salary & Amount Deducted, code here. */
    break;

default:
    printf("You didn't enter a proper ID\n");
    break;
}

To solve your exact question, use elseif. 要解决您的确切问题,请使用elseif。

If an IF statement is true then all the other elseifs under it are skipped. 如果IF语句为true,则跳过其下的所有其他elseif。

if (ID == 1) {
    Amount_Deducted = Base_Salary * 0.50;
    Net_Salary = Base_Salary - Amount_Deducted;
    printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
    printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
    printf("The Net Salary is = %.2f.\n", Net_Salary);
}

else if (ID == 2) {
        Amount_Deducted = Base_Salary * 1.50;
        Net_Salary = Base_Salary - Amount_Deducted;
        printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
        printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
        printf("The Net Salary is = %.2f.\n", Net_Salary);
    }

else if (ID == 3) {
    Amount_Deducted = Base_Salary * 2.50;
    Net_Salary = Base_Salary - Amount_Deducted;
    printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
    printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
    printf("The Net Salary is = %.2f.\n", Net_Salary);
}

else if (ID == 4) {
    Amount_Deducted = Base_Salary * 3.50;
    Net_Salary = Base_Salary - Amount_Deducted;
    printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
    printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
    printf("The Net Salary is = %.2f.\n", Net_Salary);
}

else if (ID == 5) {
    Amount_Deducted = Base_Salary * 4.50;
    Net_Salary = Base_Salary - Amount_Deducted;
    printf("The Base Salary you have entered = %.2f.\n", Base_Salary);
    printf("The Amount of salary deducted is = %.2f.\n", Amount_Deducted);
    printf("The Net Salary is = %.2f.\n", Net_Salary);
}

A cleaner approach would be to use arrays and use an index to loop over them, as your code is quite redundant, inside each IF block. 较干净的方法是在每个IF块内使用数组并使用索引对它们进行循环,因为您的代码非常冗余。 You can easily refactor it into a method, or write it inside a FOR loop to maximize code reuse and reduce code duplication. 您可以轻松地将其重构为方法,或将其写入FOR循环中以最大程度地提高代码重用性并减少代码重复。

The logic says "if ID == 1 && .. check salary range ... else print error", which means for every ID that isn't 1, you will print the error. 逻辑说“如果ID == 1 && ..检查薪水范围...否则打印错误”,这意味着对于每个不为1的ID,您都将打印错误。

I think you want to change this: 我认为您想更改此设置:

if (ID == 1 && Base_Salary >= 100 && Base_Salary <= 1000) {
    printf("Base salary is in range for ID given.\n");
}
else {
    printf("Salary must be between 100-1000 for ID 1.\n");
}

to this: 对此:

if (ID == 1) {
    if (Base_Salary >= 100 && Base_Salary <= 1000) {
        printf("Base salary is in range for ID given.\n");
    }
    else {
        printf("Salary must be between 100-1000 for ID 1.\n");
    }
}

and you'll have to change each of the other blocks too. 而且您还必须更改其他每个块。

To echo some other answers, this code would be much better if you used an array to hold your salary information and a loop to iterate over the salaries, and you could get rid of all the if/else statements which are hard to read and hard to maintain. 为了回馈其他答案,如果您使用一个数组来保存您的薪水信息并使用一个循环迭代薪水,并且可以摆脱所有难以理解的if / else语句,则此代码会更好。保持。

Continuing from the original comment, your compiler should be telling you where your initial errors lie. 从原始注释继续,您的编译器应告诉您初始错误位于何处。 If you do not warnings enabled, then get in the habit of always compiling with at least -Wall -Wextra to enable then and then read and do not accept code that compiles with any warnings. 如果未启用警告,则养成始终至少使用-Wall -Wextra进行编译以启用then的习惯,然后阅读并且不接受使用任何警告进行编译的代码。 (you are unlikely to encounter any legitimate scenario where warnings cannot be eliminated) You can also add -pedantic for additional warnings if you choose. (您不可能遇到无法消除警告的任何合法情况)。如果-pedantic ,还可以添加-pedantic以获得其他警告。

You compiler should be telling you, eg 您的编译器应该告诉您,例如

 salary.c:55:60: warning: left-hand operand of comma expression has no effect [-Wunused-value] if (ID == 3 && Base_Salary >= 5001 && Base_Salary <= 10, 000) { ^ 

It is even nice enough to give you a circumflex ( '^' ) pointing to the problem (eg you cannot include a comma within the number) 甚至可以给您指出问题的音调符号'^' )(例如,您不能在数字中包含comma

Secondly, as you begin programming in C, always validate ALL user input . 其次,在开始使用C进行编程时,请始终验证所有用户输入 If you fail to validate that a proper conversion has taken place in your use of scanf (by checking the return ), you can have zero confidence you are actually processing an actual value from that point forward in your code. 如果您无法通过使用scanf来验证是否已经进行了正确的转换(通过检查return ),则可以从零开始就对代码中的实际值进行置信度为零。 There is nothing difficult about it, just verify that the number of expected conversions did in fact take place. 没什么困难,只需验证一下预期的转换次数确实发生了即可。 You can also validate the range of the value entered at that time, eg (with a simple constant defined #define IDMAX 5 ): 您还可以验证当时输入的值的范围,例如(使用简单的常量定义的#define IDMAX 5 ):

printf ("Enter ID: ");  /* prompt for ID number & validate */
if (scanf ("%d", &ID) != 1 || ID < 1 || ID > IDMAX) {
    fprintf (stderr, "error: invalid ID\n");
    return 1;
}

note: it is highly unlikely that your Amount_Deducted is actually being computed by multiplying by a value greater than 1 , otherwise your Net_Salary would be negative . 注意:这是不可能的,你Amount_Deducted实际上正在由值大于相乘得到1 ,否则你Net_Salary将为

Finally, while there are many ways to validate the range and deduction rate, in cases similar to this, a simple lookup table created out of arrays, provides are very efficient solution opposed to a myriad of if ... else ... or switch statements. 最后,尽管有很多方法可以验证范围和扣除率,但与此类似的情况是,由数组创建的简单查找表提供了非常有效的解决方案,与无数if ... else ...switch陈述。 For example: 例如:

#include <stdio.h>

#define IDMAX 5

int main (void)   /* affirmatively indicate no arguments expected */
{
    int ID = 0,   /* initialize variables */
        range [][2] = {{   100,  1000}, /* salary range lookup */
                       {  1001,  5000},
                       {  5001, 10000},
                       { 10001, 15000},
                       { 15001, 20000}};
    float Base_Salary = 0.0,
        Amount_Deducted = 0.0,
        Net_Salary = 0.0,
        rate[] = { .05, .15, .25, .35, .45 };  /* rate lookup */

    printf ("Enter ID: ");  /* prompt for ID number & validate */
    if (scanf ("%d", &ID) != 1 || ID < 1 || ID > IDMAX) {
        fprintf (stderr, "error: invalid ID\n");
        return 1;
    }

    printf ("Enter your salary in the appropriate range: ");
    if (scanf ("%f", &Base_Salary) != 1) { /* validate entry */
        fprintf (stderr, "error: invalid Base_Salary\n");
        return 1;
    }

    /* validate Base_Salary in range */
    if (Base_Salary < range[ID-1][0] || Base_Salary > range[ID-1][1]) {
        fprintf (stderr, "error: Salary must be between %d-%d for ID %d.\n",
                range[ID-1][0], range[ID-1][1], ID);
        return 1;
    }
    else
        printf ("Base salary is in range for ID given.\n");

    Amount_Deducted = Base_Salary * rate[ID-1]; /* calculations */
    Net_Salary = Base_Salary - Amount_Deducted;

    printf ("The Base Salary you have entered = %.2f.\n", Base_Salary);
    printf ("The Amount of salary deducted is = %.2f.\n",
            Amount_Deducted);
    printf ("The Net Salary is = %.2f.\n", Net_Salary);

    return 0;   /* main is type 'int' and returns a value */
}

Example Use/Output 使用/输出示例

$ ./bin/salary
Enter ID: 1
Enter your salary in the appropriate range: 99
error: Salary must be between 100-1000 for ID 1.

$ ./bin/salary
Enter ID: 1
Enter your salary in the appropriate range: 1000
Base salary is in range for ID given.
The Base Salary you have entered = 1000.00.
The Amount of salary deducted is = 50.00.
The Net Salary is = 950.00.

$ ./bin/salary
Enter ID: 2
Enter your salary in the appropriate range: 1000
error: Salary must be between 1001-5000 for ID 2.

Always compile with warnings enabled, and do not except any code until it compiles without warning, and your debug time will be greatly reduced. 始终在启用警告的情况下进行编译,除非在没有警告的情况下进行编译,否则不要编译任何代码,否则调试时间将大大减少。 There are a few additional pointers included in the code comments as well. 代码注释中还包含一些其他指针。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。

final note: While not an error, the standard style for C generally avoids Mixed_Case and caMelCase variable names in favor of all lower-case and reserving upper-case for macros and preprocessor defines. 最后说明:尽管不是错误,但C的标准样式通常避免使用Mixed_CasecaMelCase变量名,而将所有小写字母都保留为大写 ,并为宏和预处理程序定义保留大写字母 Your variable names have been left as-is to help you follow along. 您的变量名将保持不变,以帮助您进行后续操作。 This is a nit, but it is worth being aware of. 这是一个特例,但值得注意。

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

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