家庭作业初学者C++:在整数加法期间无法执行类型转换

Homework Beginner C++: Unable to perform Type Casting during addition of integers

为了帮助我们理解 C++ 中的类型转换,我们需要执行两个 int 的加法运算,如下所示。如果我们分别提供两个 int 作为 45,输出应该是 4 + 5 = 9.

我尝试关注 this type casting tutorial 但没有成功。有人可以给我一些提示吗?

逐字引用作业。

Your friend wrote a program called an adder. The adder is supposed to take two numbers inputted by a user and then find the sum of those numbers, but it’s behaving oddly.

Your first task is to figure out what is wrong with the adder. Your second task is to fix it.

Hint(s) to identify the problem
Try entering 1 and 1. You expect the output to be 2 but you get 11 instead. Similarly, if you enter 3 and 4, you expect the output to be 7 but you get 34. Remember, string concatenation also uses the + operator.

Hint(s) to identify the solution
The + operator functions differently based on the type of data that comes before and after it. What data types will cause the + operator to calculate a mathematical sum? What data type is present in the program now? How do you convert from one data type to another? Check out the Type Casting page for some idea

#include <iostream>
using namespace std;

int main() {
  
  string num1;
  string num2;
  cout << "Type the first whole number and then press Enter or Return: ";
  cin >> num1;
  cout << "Type the second whole number and then press Enter or Return: ";
  cin >> num2;
  

  string sum = num1 + num2;
  cout << ( num1 + " + " + num2 + " = " + sum )  << endl;

  
  return 0;
  
}

代码的问题在于它在执行 字符串连接 而需要执行 算术加法 时。因此,您需要将用户的输入转化为数字变量,而不是字符串。作业甚至暗示了这一点。

但是:

Check out the Type Casting page for some idea

这对这项任务来说是个糟糕的建议,因为您无法通过 类型转换 解决问题。

您需要:

  • 更改代码以使用 int 变量而不是 string 变量。这是首选解决方案,例如:
#include <iostream>
using namespace std;

int main() {
  
  int num1;
  int num2;
  cout << "Type the first whole number and then press Enter or Return: ";
  cin >> num1;
  cout << "Type the second whole number and then press Enter or Return: ";
  cin >> num2;

  int sum = num1 + num2;
  cout << num1 << " + " << num2 << " = " << sum << endl;

  return 0;
  
}
  • 否则,如果你想继续使用string变量,你需要转换(不是类型转换!)它们的值在运行时转换为 int 值,然后再转换回来,例如:
#include <iostream>
#include <string>
using namespace std;

int main() {
  
  string num1;
  string num2;
  cout << "Type the first whole number and then press Enter or Return: ";
  cin >> num1;
  cout << "Type the second whole number and then press Enter or Return: ";
  cin >> num2;

  int sum = stoi(num1) + stoi(num2);
  cout << ( num1 + " + " + num2 + " = " + to_string(sum) )  << endl;

  return 0;
  
}

如果你对一个字符或字符串进行类型转换,它会被转换成它的等效 ASCII 值,你需要使用 stoi 或从每个数字位置的“0”中减去(有点重复的工作)使用 stoi