【问题标题】:Why is the modulus operator giving wrong answer?为什么模数运算符给出错误的答案?
【发布时间】:2016-09-24 00:35:14
【问题描述】:
#include<iostream>
#include<string>
#include<sstream>

using namespace std;

int main(){
    stringstream ss;
    ss << 32;
    string str = ss.str();
    cout << str << endl
         << str[0] << endl
         << str[1] <<endl
         << str[0]%10;
    return 0;
}

输出是:

32
3
2
1

相反,最后一行应该是 3 as 3%10=3。

【问题讨论】:

  • str[0] 为 51,51%10 为 1
  • 打印cout &lt;&lt; +str[0];cout &lt;&lt; (str[0] - '0') 会得到什么?

标签: c++ string io stringstream mod


【解决方案1】:

因为您将它与 ascii 值(即 51(0 为 48))进行比较,修改后得到 1。您应该减去“0”或 48 才能从汽车中获得实数。

【讨论】:

  • 我建议总是减去“0”。 '0' 的意图不仅以 48 不明显的方式立即显而易见,而且它还将移植到大多数不基于 ASCII 并且没有以不寻常的方式排列数字的系统。
【解决方案2】:

字符的表示不同于数字的表示。即使str[0] 处的字符是 3,它的 ASCII 码(即其数字表示)为 51 的字符 3。由于在执行需要整数的操作时,字符可以隐式转换为整数,因此您的编码正在执行 51%10这是1。

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2014-02-24
    • 1970-01-01
    相关资源
    最近更新 更多