首页 > 解决方案 > 当我在 cmd 或 VScode 上运行时,C++ 程序不输出(但在 repl.it 上它会输出)

问题描述

我有我写的这个 C++ 程序,它对向量求和:

#include <cmath>
#include <iostream>

using namespace std;

const float half_Pi = acos(0.0);

double *vectorSum(double *lengths, double *angels, int size, bool cartazian) {
  double Cx, Cy, *res;
  for (int i = 0; i < size; i++) {
    Cx += cos(angels[i] / 90 * half_Pi) * lengths[i];
    Cy += sin(angels[i] / 90 * half_Pi) * lengths[i];
  }
  if (cartazian) {
    res[0] = Cx;
    res[1] = Cy;
  } else {
    res[0] = sqrt(Cx * Cx + Cy * Cy);
    res[1] = atan(Cy / Cx) * 90 / half_Pi;
  }
  return res;
}

int main() {
  int numVectors, i = 0, carta;
  bool cartazian;
  cout << "enter number of vectors to sum: ";
  cin >> numVectors;
  double *lengths = new double[numVectors];
  double *angels = new double[numVectors];
  while (i < numVectors) {
    cout << "enter length " << i + 1 << ": ";
    cin >> lengths[i];
    cout << "enter angel " << i + 1 << ": ";
    cin >> angels[i];
    i++;
  }
  cout << "would you like the sum presented in x and y? enter 1 for yes and 0 "
          "for no: ";
  cin >> carta;
  if (carta == 0)
    cartazian = false;
  else if (carta == 1)
    cartazian = true;
  else
    throw("must enter either 0 or 1");
  double *totalVector = vectorSum(lengths, angels, numVectors, cartazian);
  if (cartazian)
    cout << "Vx = " << totalVector[0] << endl
         << "Vy = " << totalVector[1] << endl;
  else
    cout << "length = " << totalVector[0] << endl
         << "angle = " << totalVector[1] << "\u00B0" << endl;
  return 0;
}

我已经能够在 repl.it 上完全运行它,但是当我尝试在 VScode(使用 minGW)或 cmd 上运行它时,它运行良好,直到我完成输入(不显示结果)。为什么不显示结果?是因为throw(尝试过但仍然没有)吗?我不认为这是因为数学函数,因为我在另一个测试文件上运行它们很好。我该如何解决?

标签: c++visual-studio-codecmd

解决方案


由于您将数据分配给未初始化的指针 res ,该函数vectorSum具有未定义的行为,就好像它指向有效内存一样。

请注意,您还有未定义的行为,因为您没有初始化值CxCy,而是开始添加它们。

第一个问题的一个天真的解决方法是分配内存,然后让调用者负责释放它,或者使用智能指针或 a std::vector<double>,但实际上你需要的只是类似的东西std::pair<double, double>。至于第二个问题,就像将值初始化为零一样简单。

请注意,这std::pair是在中定义的,<utility>因此您需要将其包括在内。

std::pair<double, double> vectorSum(double *lengths, double *angels, int size, bool cartazian)
{
  std::pair<double, double> res;
  double Cx = 0, Cy = 0;
  for (int i = 0; i < size; i++) {
    Cx += cos(angels[i] / 90 * half_Pi) * lengths[i];
    Cy += sin(angels[i] / 90 * half_Pi) * lengths[i];
  }
  if (cartazian) {
    res.first = Cx;
    res.second = Cy;
  } else {
    res.first = sqrt(Cx * Cx + Cy * Cy);
    res.second = atan(Cy / Cx) * 90 / half_Pi;
  }
  return res;
}

来电:

std::pair<double, double> totalVector = vectorSum(lengths, angels, numVectors, cartazian);
if (cartazian)
  cout << "Vx = " << totalVector.first << endl
       << "Vy = " << totalVector.second << endl;
else
  cout << "length = " << totalVector.first << endl
       << "angle = " << totalVector.second << "\u00B0" << endl;

最后一点是要注意在代码中正确拼写。例如,正确的拼写是:

  • 角度
  • 笛卡尔

推荐阅读