C语言:计算分数加减表达式的值

 

#include <stdio.h>
int main()
{
    int n, i;
    double sum = 0;
    scanf("%d", &n);
    for ( i = 1; i <= n; ++i) {
        if (i % 2 == 0) {
            sum -= 1.0 / i;  //分子必须写成1.0,否则会发生编译错误
        }
        else {
            sum += 1.0 / i;  //同上
        }
    }
    printf("%.4f", sum);
    return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过栈来实现中缀表达式计算。具体步骤如下: 1. 定义一个栈,用于存储数字和运算符。 2. 从左到右遍历中缀表达式中的每一个字符。 3. 如果当前字符是数字,则将其入栈。 4. 如果当前字符是运算符,则取出栈顶的两个数字进行运算,并将结果入栈。 5. 遍历完整个中缀表达式后,栈内只剩下一个元素,即为表达式计算结果。 以下是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define STACK_SIZE 100 typedef struct { int data[STACK_SIZE]; int top; } Stack; void init(Stack *s) { s->top = -1; } void push(Stack *s, int value) { if (s->top >= STACK_SIZE - 1) { printf("Stack overflow"); exit(1); } s->data[++s->top] = value; } int pop(Stack *s) { if (s->top < 0) { printf("Stack underflow"); exit(1); } return s->data[s->top--]; } int main() { Stack s; char c; char expr[STACK_SIZE]; int len, i, num1, num2; init(&s); printf("Enter an infix expression: "); fgets(expr, STACK_SIZE, stdin); len = strlen(expr); for (i = 0; i < len; i++) { c = expr[i]; if (isdigit(c)) { push(&s, c - '0'); } else if (c == '+') { num2 = pop(&s); num1 = pop(&s); push(&s, num1 + num2); } else if (c == '-') { num2 = pop(&s); num1 = pop(&s); push(&s, num1 - num2); } else if (c == '*') { num2 = pop(&s); num1 = pop(&s); push(&s, num1 * num2); } else if (c == '/') { num2 = pop(&s); num1 = pop(&s); push(&s, num1 / num2); } } printf("Result: %d", pop(&s)); return 0; } ``` 注意,此代码仅适用于只包含加减乘除的中缀表达式。对于包含其他运算符的表达式,需要进行相应修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值