循环中的计数器比预期的要大得多
我正在参加 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论