c++ - 为什么我的模数计算给我盒子?

标签 c++

当前输入和输出代码如下:

预期输出:

当我编译并运行程序并专门输入一个 4 位数字测试(例如“9876”)时,我的答案实际上是 4 个框。答案应该是 3197,但我真的不知道该怎么做。我认为数据类型有问题,但我真的不确定如何解决这个问题。

输入数据:

9876

输出数据:

????

预期数据:

3197

到目前为止,这是我的代码:

#include <iostream> //access input output related code
#include <string>
#include <math.h>
#include <sstream>
#include <ctype.h>
#include <iomanip>
using namespace std; // use the C++ standard namespace which includes cin and
                     // cout

int main() {
  string encodednumber, decodednumber;
  int temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8;
  char initialnumber[10];

  cout << "Please enter a number: " << endl;
  cin.getline(initialnumber, 10);
  string str = initialnumber;
  int numlength = str.length();
  cout << "Number contains " << numlength << " digits" << endl;

  switch (numlength) {
  case 4:
    temp1 = initialnumber[0];
    initialnumber[0] = ((temp1 + 4) % 10);
    temp2 = initialnumber[1];
    initialnumber[1] = ((temp2 + 3) % 10);
    temp3 = initialnumber[2];
    initialnumber[2] = ((temp3 + 2) % 10);
    temp4 = initialnumber[3];
    initialnumber[3] = ((temp4 + 1) % 10);
    encodednumber = initialnumber;
    cout << "\nThe encoded number is " << encodednumber << endl;
    break;
  default:
    cout << "Not a valid input, re enter the number" << endl;
  }
  return 0;
}

最佳答案

没错,就是数据类型。您忽略了 charint 之间的区别,并假设您可以在它们之间自动转换。

要将数字字符转换为相应的整数,您必须减去'0'

temp1 = initialnumber[0] - '0';

要将整数转换为 char,则相反,您必须添加 '0'

initialnumber[0] = ((temp1 + 4) % 10) + '0';

所有字符都编码为整数。数字“0”到“9”保证由连续整数编码(“0”具有最低值)。因此,从字符中减去 '0' 会将编码值转换为相应的整数值。

关于c++ - 为什么我的模数计算给我盒子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52055249/

相关文章:

c++ - C++ Boost 中的线程数组

c++ - 如何知道指针指向堆还是栈?

c++ - 模板成员变量特化

c++ - 为什么转换不起作用?

c++ - 将输出流中行首的一个字符替换为另一个字符

java - 从 Qt C++ 调用 Java 函数

c++ - 为什么 move 指针变量不会将其设置为空?

c++ - 我没有得到运算符重载

c++ - #define Terminal ((arc*)1) 是什么意思?

c++ - MinGW64 和 "conflicting declaration of C function int select(...)"