gpt4 book ai didi

c - 制作计算器

转载 作者:行者123 更新时间:2023-11-30 18:54:43 26 4
gpt4 key购买 nike

当我除以 2 个数字(10/2/2)时,如何才能得到正确的解决方案。另外,当一个数字除以另一个数字时,如何让它找到余数。

How would I begin with being able to divide by 2 or more numbers? With if-else statements.

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

void main()
{
char operation = 0;
double num1=0.0 ;
double num2=0.0 ;
printf("Enter the calculation\n");
scanf("%f %c %f", &num1, &operation, &num2);

switch (operation) {
case '+':
printf("= %f\n", num1 + num2);
break;
case '-':
printf("= %f\n", num1 - num2);
break;
case '*':
printf("= %f\n", num1*num2);
break;
case '/':
printf("= %f\n", num1 /(double)num2);
break;
case '%':
printf("= %f\n", num1 % (double)num2);
break;
default:
printf("Error!\n");
break;
}
system("pause");
}

最佳答案

要获得您要查找的余数,您必须将两边都转换为 int:

    printf("= %d\n", (int)num1 % (int)num2);

要解析复杂的表达式,您需要完全不同的东西。现在您的代码只执行单个操作,因此可以忽略运算符优先级。但是当你进行链式操作时,你需要注意这一点。与 1 - 2 * 3 类似,您的代码应该执行 2*3,然后添加 1。最简单的方法是使用递归的解析器:http://en.wikipedia.org/wiki/Recursive_descent_parser

以下是基本/简单的规则概念:

line       -> expression <EOF>
expression -> factor + expression
factor - expression
factor
factor -> term * factor
term / factor
term % factor
term
term -> ( expression )
<number>

然后,每个规则的代码看起来大致如下:

double read_factor(...) {
double first = read_term(...);
double second = 0.0;
switch(peek_next_symbol()) {
case '*':
consume_symbol();
second = read_term();
return first * second;
case '/':
consume_symbol();
second = read_term();
if (second == 0)
throw std::logic_error("div/0");
return first / second;
case '%':
consume_symbol();
second = read_term();
if (second == 0)
throw std::logic_error("mod/0");
return (double)((int)first % (int)second);
default:
return first;
}
}

然后这个术语看起来隐约像这样:

double read_term() {
double first = 0.0;
switch(peek_next_symbol()) {
case '(':
consume_symbol();
first = read_expression();
if (peek_next_symbol() != ')')
throw std::logic_error("missing )");
consume_symbol();
default:
return read_number();
}
}

我引用的每个函数都相对复杂,并且传递了大量的状态。现在我已经简要解释了该理论,这是一个很小的工作示例:http://ideone.com/wVqRw

关于c - 制作计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29782597/

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