输入一行只包含加法和乘法的算式,输出结果

img


为什么在vs运行不了?
提交到OJ系统显示超时?为什么呀到底是为什么?

全部用C语言试试:

#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
    int x,y,ans=0 ;
    char fu;
    //cin >> x;
    scanf_s("%d",&x);
    while(scanf_s("%c",&fu))
    {
        if(fu=='\n')
            break;
        else
        {
            //cin >> y;
            scanf_s("%d",&y);
            if(fu=='+')
            {
                ans=ans+x;
                x=y;
               // break;   //当为加的时候,执行到这里的时候就需要用breakwhile循环,不然就输出不了结果
            }
            if(fu=='*')
            {
                x=x*y;
               // break;  //当为*的时候,执行到这里的时候就需要用breakwhile循环,不然就输出不了结果
            }
        }
    }
    ans=ans+x;
    //cout <<ans<< endl;
    printf_s("%d\n",ans);
    system("pause");
    return 0;
}

你这是C++代码,scanf是C语言的输入函数,建议最好不要混用,如果想要使用的话要额外引入C的头文件#include<stdio.h>

#include <iostream>
#include <sstream>
#include <stack>
#include <stdexcept>

// Calculates a op b, where op is + or *
double calculate(double a, char op, double b) {
  switch (op) {
  case '+':
    return a + b;
  case '*':
    return a * b;
  default:
    throw std::runtime_error("invalid operator");
  }
}

// Compares the priority between op1 and op2.
// Returns 0 if op1 == op2, -1 if op1 < op2, 1 if op1 > op2
int compare(char op1, char op2) {
  if (op1 == op2)
    return 0;
  if (op1 == '+' && op2 == '*')
    return -1;
  else
    return 1;
}

int main() {
  std::stack<char> ops;    // operator stack
  std::stack<double> nums; // number stack

  // Read a line from the standard input.
  std::string line;
  std::getline(std::cin, line);
  std::istringstream ss(line);

  double x;
  char op;
  ss >> x;                // Read the first number.
  nums.push(x);           // Push the first number to stack.
  while (ss >> op >> x) { // Read the next operator and number.
    // Do the calculation in the stack as long as the priority of the top
    // operator is not less than current operator.
    while (!ops.empty() && compare(ops.top(), op) >= 0) {
      auto a = nums.top();
      nums.pop();
      auto b = nums.top();
      nums.pop();
      nums.push(calculate(a, ops.top(), b));
      ops.pop();
    }
    ops.push(op);
    nums.push(x);
  }

  // Do the calculation in the stack.
  while (!ops.empty()) {
    auto a = nums.top();
    nums.pop();
    auto b = nums.top();
    nums.pop();
    nums.push(calculate(a, ops.top(), b));
    ops.pop();
  }

  // Write the result.
  std::cout << nums.top() << std::endl;

  return 0;
}
$ g++ -Wall main.cpp
$ ./a.out
1 + 2*3*4 + 5
30