【问题标题】:always returning 466750944 in c++ calculations script在 C++ 计算脚本中总是返回 466750944
【发布时间】:2018-09-21 08:19:32
【问题描述】:
#include <iostream>
using namespace std;
multiplication() {
  int x;
  int y;
  int sum;
  sum = y * x;

  cout << "multiplication" << endl;
  cout << "enter first number for multiplication: ";
  cin >> x;
  cout << "enter second number for multiplication: ";
  cin >> y;
  cout << "your product is: " << sum <<endl;
  return 0;
}
void division (){
  cout << "division" << endl;

}
void addition (){
  int y;
  int x;
  int sum = x * y;
  cin >> x;
  cin >> y;
  cout << sum;
}
void subtraction (){

}

int main()
{cout << "enter 1 for multiplication, enter 2 for division, enter 3 for addition, and enter 4 for subtraction"<<endl;
  int math;
  cin >> math;
  switch(math){

    case 1:
      multiplication();
      break;
    case 2:
      division();

    default:
      cout << "it dont work ooga booga"<<endl;
      break;
    case 3:
      addition ();
      break;
    case 4:
      subtraction();}
  return 0;
}

这是我要运行的脚本,我在 code::blocks 中运行,如果有问题会导致它始终返回 466750944 请告诉我,以便我可以在这方面进行更多工作,这可能是我的问题如果有人也可以在代码块或其他 ide 中运行此脚本并发布他们的结果,将不胜感激,谢谢

【问题讨论】:

  • multiplication() { 是 C++ 中的语法错误。
  • 总是尽可能严格地打开编译器警告;这将解决包括这个问题在内的各种问题。
  • int sum = x * y 不声明关系。它是一个在遇到时执行的语句,结果 value 被赋值给sum。之后,sum 不知道xy 并且独立于它们。赋值后更改xy 不会更改sum 的值。

标签: c++


【解决方案1】:

当您说 sum = x * y 在定义时进行评估时,它不是数学中的公式,稍后在渲染时对其进行评估。

sum = x * y语句执行时,xy没有初始化,所以sum的值基本上是垃圾。

要查看此行为的实际效果,请在调试器中单步执行您的代码并查看xysum 的值。

要么将其移至 xy 被正确定义,要么将其移至函数中,例如:

int sum(int x, int y) {
  return x * y;
}

【讨论】:

  • @FrançoisAndrieux 相应添加。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多