简体   繁体   English

while 循环中的奇怪错误 (C++)

[英]Strange bug in a while loop (C++)

I'm trying to make a program that works with a simple algorithm.我正在尝试制作一个使用简单算法的程序。

But for some reason, I get a strange bug (below is the simplified version of the program).但是由于某种原因,我遇到了一个奇怪的错误(以下是程序的简化版本)。

#include "stdafx.h"
#include <iostream>
#include <string>

using std::cout;
using std::string;

void find(int arr[], string name)
{
    int t = 8;
    int i = 0;
    int v = 0;

    // t should become equal to the smallest int of the array after this.


    while (arr[i])
    {
        if (arr[i] < t)
        {
            t = arr[i];
        }
        ++i;
    }

    /* When this statement below gets executed t gets what looks like a                 
    random value for some reason */
    cout << arr[t] << '\n';
    for (int b = 0; b < 2; ++b)
    {
        if (t == arr[b])
        {
            v = b;
        }
    }

    /* Again, arr[v] gets what looks like a random number */
    cout << "The cheapest " << name << " is number " << arr[v] << ".";
}



int main()
{

    /* [0] = "Cost for Steve"
       [1] = "Cost for Mark"
       [2] = "Cost for Andrew" */

    int cleaning[] = { 5, 4, 7 };
    int cooking[] = { 3, 6, 4 };
    int babysitting[] = { 7, 6, 3 };

    cout << "Number 1: Steve, Number 2: Mark, Number 3: Andrew.\n";

    find(cleaning, "cleaner");
    find(cooking, "cook");
    find(babysitting, "babysitter");




/* This is to prevent the console application from quitting */

    while (true)
    {

    }

}

I'm sure there is something wrong in the for and the while loop, but what?我确定 for 和 while 循环中存在问题,但是什么?

If you're reading my code and some text or variable name seems foreign to you, chances are that I forgot to translate it (this is originally written in Italian).如果您正在阅读我的代码并且某些文本或变量名称对您来说似乎很陌生,那么很可能是我忘记翻译它(这最初是用意大利语编写的)。

Thanks for taking your time to read this.感谢您花时间阅读本文。

EDIT: Thanks to @Tar I fixed the first part of the program, but the part which says The (name) that costs less is n. (arr[v]).编辑:感谢@Tar,我修复了程序的第一部分,表示The (name) that costs less is n. (arr[v]).部分The (name) that costs less is n. (arr[v]). The (name) that costs less is n. (arr[v]). still gives me a random number, I compiled and ran the program, the output is:仍然给我一个随机数,我编译并运行了程序,输出是:

Number 1: Steve, Number 2: Mark, Number 3: Andrew.
4
The cheapest cleaner is number 4.
3
The cheapest cook is number 3.
3
The cheapest babysitter is number 7.

That is obviously wrong as it should say that the cheapest cleaner is number 2, the cheapest cook is number 1 and the cheapest babysitter is number 3.这显然是错误的,因为应该说最便宜的清洁工排在第 2 位,最便宜的厨师排在第 1 位,最便宜的保姆排在第 3 位。

PS: As soon as everything is fixed I will take the part which prints the cheapest price out. PS:一旦一切都解决了,我会把最便宜的那部分打印出来。

The problem is within your first while loop in find :问题出在find第一个while循环中:

while (arr[i]) // while the element at arr[i] is NOT 0
{
    if (arr[i] < t)
    {
        t = arr[i];
    }
    i++;
}

Here you continuously evaluate elements in arr for whether they are not 0 .在这里,您不断评估arr元素是否为0 This is not correct.这是不正确的。 You've declared your arrays as:您已将数组声明为:

int cleaning[3] = { 5, 4, 7 };
int cooking[3] = { 3, 6, 4 };
int babysitting[3] = { 7, 6, 3 };

None of these contain 0 , so your while loop will run indefinitely and you'll be reading past the memory for each array which is not good news.这些都不包含0 ,因此您的while循环将无限期运行,并且您将读取每个数组的内存,这不是好消息。

Consider using std::vector instead, and see how much clearer and safer your code becomes:考虑改用std::vector ,看看你的代码变得更清晰、更安全:

#include <vector>
#include <iostream>

void find(const std::vector<int>& numbers)
{
    auto t = 8;
    // Look through each element in the container:
    for(auto number : numbers)
    {
        if (number < t)
        {
            t = number;
        }
    }
    std::cout << t << std::endl;
}

int main()
{
    std::vector<int> cleaning = {5, 4, 7};
    find(cleaning);
}

Above all, I want to make a statement: I am not an English-speaker, so if I said wrong words, please excuse me.最重要的是,我想声明:我不会说英语,所以如果我说错的话,请见谅。
I think this question is not very difficult.我觉得这个问题不是很难。 I fixed your algorithm and output format.我修正了你的算法和输出格式。 Actually, I almost rewrote it.实际上,我几乎重写了它。
In my view, your code seems kind of naive.在我看来,您的代码似乎有点幼稚。 If you only learnt C++ syntax, there is a long way to study algorithm.如果你只学过C++语法,那么学习算法还有很长的路要走。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int find(const vector<int>& numbers) {
    int minVul = numbers[0];
    int rank = 0;

    for (int i = 1; i < numbers.size(); i++)
    {
        if (minVul > numbers[i])
        {
            minVul = numbers[i];
            rank = i;
        }
    }
    return rank;
}



int main() {

    vector<string> name = { "steve","mark","andrew" };
    /* [0] = "Cost for steve"
    [1] = "Cost for mark"
    [2] = "Cost for andrew" */

    vector<int> cleaning = { 5, 4, 7 };
    vector<int> cooking = { 3, 6, 4 };
    vector<int> babysitting = { 7, 6, 3 };

    int cleaner = find(cleaning);
    cout << "Cleaning:" << name[cleaner] << " costs least in " << cleaning[cleaner] << endl;
    int cooker = find(cooking);
    cout << "Cooking:" << name[cooker] << " costs least in " << cooking[cooker] << endl;
    int babysitter = find(babysitting);
    cout << "Babysitter:" << name[babysitter] << " costs least in " << babysitting[babysitter] << endl;

    system("pause"); //This is a common skill to prevent the console application from quitting.
    return 0;
}

Outputs:输出:

Cleaning:mark costs least in 4
Cooking:steve costs least in 3
Babysitter:andrew costs least in 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM