gpt4 book ai didi

c - 在 C 中将算术表达式应用于用户提供的 2 个二进制数的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 17:47:15 25 4
gpt4 key购买 nike

我正在编写一个程序,它接受用户的 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);
}

}

最佳答案

由于表达式char(而不是char[]),因此您可以使用switch-案例:

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

您可能还想添加默认值,以防用户输入无效的运算符。

关于c - 在 C 中将算术表达式应用于用户提供的 2 个二进制数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com