0

我正在解决一个寻找算术表达式最大值的问题。但是我在输入表达式时遇到问题,因为没有固定的字符。

输入格式:

  • 输入的唯一行包含一个长度为 2n + 1 的字符串 s,其中包含符号 s0 、 s1 、 。. . , s2n。
  • s 偶数位置的每个符号都是一个数字(即 0 到 9 的整数)
  • 而奇数位置的每个符号是 {+,-,*} 的三个操作之一。

但我想要不同数组中的数字和符号(int 数组中的数字和 char 数组中的操作)作为我的解决方案。

这就是我最初实现的方式:

  string s;
  std::cin >> s;

  n=s.size();
  cout<<"n= "<<n<<endl;

  vector<long long> no;
  vector<char> ops;

  for(int i = 0; i <n; i++)
  {
    if(i%2==0)
    {
      no.push_back(s[i]);
    }
    else{
      ops.push_back(s[i]);
    }
  }

但我无法获得所需的输入,而是得到这个:

INPUT:
5-8+7*4-8+9

OUTPUT:
n = 11
no[0] = 53
no[1] = 56
no[2] = 55
no[3] = 52
no[4] = 56
no[5] = 57
ops[0] = -
ops[1] = +
ops[2] = *
ops[3] = -
ops[4] = +

我还尝试了另一种解决方案:

  vector<long long> no;
  vector<char> ops;

  int i=0;
  while(cin)
  {

    cout<<"i= "<<i<<endl;
    if(i%2==0)
    {
      int s;
      cin>>s;
      if(s=='\0')
      {
        exit();
      }
      cout<<"s= "<<s<<endl;
      no.push_back((int)s);
      cout<<"no= "<<no[i/2]<<endl;
    }
    else
    {
      char s;
      cin>>s;
      if(s=='\0')
      {
        exit();
      }
      cout<<"s= "<<s<<endl;
      ops.push_back(s);
      cout<<"ops= "<<ops[(i-1)/2]<<endl;
    }
    i++;
  }

但这进入了无限循环。

请帮帮我

4

1 回答 1

0

您的输出似乎是正确的,但正如评论中已经提到的,您的值被读取为字符,而不是数字,因此需要进行转换。

为此,了解 ASCII 中的数字具有以下值可能会有所帮助:

Character ASCII-code value
      '0'         48     0
      '1'         49     1
      '2'         50     2
      '3'         51     3
      '4'         52     4
      '5'         53     5
      '6'         54     6
      '7'         55     7
      '8'         56     8
      '9'         57     9

如何从字符值中获取值?简单的 :

value(<character>) = ASCII_code(<character>) - ASCII_code('0'), or:
                   = ASCII_code(<character>) - 48
于 2020-06-20T08:55:48.400 回答