循环中的计数器比预期的要大得多

发布于 2025-01-19 16:28:34 字数 981 浏览 2 评论 0原文

我正在参加 HackerRank 挑战,并被指派完成这个问题:

给定一个整数数组,计算其正数、负数和零元素的比率。在新行上打印每个分数的小数值,并在小数点后保留几位。

我想出了这个代码:

void plusMinus(vector < int > arr, int size) {
  int i, j, k = 0;
  int total = size;

  double ratio;

  while (total >= 0) {
    if (arr[total] <= 1) {
      i = i + 1;

    } else if (arr[total] >= 1) {
      j = j + 1;

    } else {

      k = k + 1;

    }

    total = total - 1;

  }

  cout << i << " " << j << " " << k << endl;

  ratio = i / size;

  cout << ratio << endl;

  ratio = j / size;

  cout << ratio << endl;

  ratio = k / size;

  cout << ratio << endl;

}

但是每当我去运行代码时,这就是输出:

下载 6 -4 3 -9 0 4 1

你的输出 32855668 32855499 0 5.47594e+06 5.47592e+06 0

预期输出

下载 0.500000 0.333333 0.166667

数组的实际大小是6,我在程序开始时已经验证过是6。问题一定出在我的 while 循环中,计数器嵌套在“if else”语句中。我知道循环不会无限,因为我已经放置了一个“cout”语句并看到它对循环迭代进行了倒计时。

I'm working on a HackerRank challenge and I've been assigned to finish this problem:

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.

I came up with this code:

void plusMinus(vector < int > arr, int size) {
  int i, j, k = 0;
  int total = size;

  double ratio;

  while (total >= 0) {
    if (arr[total] <= 1) {
      i = i + 1;

    } else if (arr[total] >= 1) {
      j = j + 1;

    } else {

      k = k + 1;

    }

    total = total - 1;

  }

  cout << i << " " << j << " " << k << endl;

  ratio = i / size;

  cout << ratio << endl;

  ratio = j / size;

  cout << ratio << endl;

  ratio = k / size;

  cout << ratio << endl;

}

But whenever I go to run the code, this is the output:

Download
6
-4 3 -9 0 4 1

Your Output
32855668 32855499 0
5.47594e+06
5.47592e+06
0

Expected Output

Download
0.500000
0.333333
0.166667

The actual size of the array is 6, and I have verified that it is six at the beginning of the program. The problem must be in my while loop with the counters nested in the "if else" statements. I know the loop is not going to infinity because I have put a "cout" statement and seen it count down the loop iterations.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文