1

尝试在 C 中编写一个简单的计算器。如果未输入字母“A”、“B”、“C”或“D”,我会卡住程序终止,否则继续。即使我输入了一个有效的字符,它也永远不会继续。

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

int main()
{
    char letter;
    float num1,num2;
    printf("What operation would you like to perform?\n\tA) Addition\n\tB) Subtraction\n\tC) Multiplication\n\tD) Division\n\n");
    scanf("%c", &letter);

    if (letter != 'A' || letter != 'B' || letter != 'C' || letter != 'D')
      printf("Not a valid operation\n");
        return 1;

    printf("Please enter first number: ");
    scanf("%f", &num1);
    printf("Please enter second number: ");
    scanf("%f", &num2);

    if (letter == 'A' || letter == 'a')
        printf("The sum of %f and %f, is %f\n", num1, num2, num1 + num2);

    else if (letter == 'B' || letter == 'b')
        printf("The difference of %f and %f, is %f\n", num1, num2, num1 - num2);

    else if (letter == 'C' || letter == 'c')
        printf("The product of %f and %f, is %f\n", num1, num2, num1 * num2);

    else if (letter == 'D' || letter == 'd')
        printf("The quoation of %f and %f, is %f\n", num1, num2, num1 / num2);
    else 
        printf("The operation was not valid");
    return 0;

}

谢谢您的帮助。

4

3 回答 3

3
if (letter != 'A' || letter != 'B' || letter != 'C' || letter != 'D')
  printf("Not a valid operation\n");
    return 1;

这部分是问题所在。虽然return 1;是缩进的,但它会执行,因为它不是if块的一部分。此外,您使用了错误的运算符,您的条件语句显示为“如果字母不是 A 或字母不是 B ...”,这总是正确的,因为字母不能同时是A两者B。您需要封装这两个语句并使用&&运算符,如下所示:

if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')
{
    printf("Not a valid operation\n");
    return 1;
}

在 C 中,缩进对编译器毫无意义。如果您需要根据条件执行多个语句,则必须使用and将它们包装成复合语句{}

于 2013-09-14T01:35:04.017 回答
0

You check

 if (letter != 'A' || letter != 'B' ...)

Ok - if letter is 'B', then it is not A, and the program stops testing there and prints your failure condition and returns.

On the other hand, if letter was 'A', it would not be 'B', and so it would fail the second test instead, and fail there.

What you want:

if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')

Alternately, you could use the C function "strchr" which searches for a character in a string.

if (!strchr("ABCDabcd", letter)) // returns NULL, which is false, if no match
{
    printf("Invalid operation");
    return 1;
}
于 2013-09-14T01:45:43.013 回答
0

Try:

if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')
...
于 2013-09-14T01:46:11.350 回答