0

我正在编写一个程序,它接受来自用户的 2 个二进制数。然后用户选择一个算术表达式 (+ - / * %) 以应用于这些数字。我有一般的输入代码,但不知道下一步该去哪里。我对 C 语言相当陌生。这是我到目前为止所拥有的。

#include <stdio.h>

int main(){

int number1, number2;
char expression;

//Basic instructions at the beginning of the program
printf("This is a program to execute arithmetic in binary.\n");
printf("The program will ask you for input in the form of two binary numbers separated byan arithmetic expression (+ - / * %).\n");
printf("The binary numbers must be only 1's and 0's and a maximum of seven digits.\n");
printf("You may exit the program by typing 'exit'.\n");

//Obviously an incomplete do statement, need a loop
do  {
//Getting input from the user
    printf("\nEnter first binary number: ");
    scanf("%d", &number1);
    printf("Enter second number: ");
    scanf("%d", &number2);
    printf("Which expression would you like (+ - / * %): ");
    scanf("%c", &expression);   
    }

}
4

1 回答 1

0

由于expression是 a char(而不是char[]),您可以使用switch- case

int result;
switch(expression){
    case '+':
        result=number1+number2;
        break;
    case '-':
        result=number1-number2;
        break;
    case '*':
        result=number1*number2;
        break;
    case '/':
        result=number1/number2;
        break;
}

您可能还想添加一个default,以防用户输入了无效的运算符。

于 2013-09-25T01:01:29.560 回答