程序崩溃并且不显示正确的输出

Program crashes and does not display correct output

所以我正在为我的 c++ class 解决一个非常 "basic" 的问题并且遇到了一些错误。问题是这个

An interesting problem in number theory is sometimes called the “necklace problem.” This problem begins with two single-digit numbers. The next number is obtained by adding the first two numbers together and saving only the ones-digit. This process is repeated until the “necklace” closes by returning to the original two numbers. For example, if the starting numbers are 1 and 8, twelve steps are required to close the “necklace”: 18976392134718 Write a program that asks the user for two starting numbers, and then displays the sequence and the number of steps taken. The program output should look similar to: Enter first number: 1 Enter ssecond number: 8 18976392134718 Your numbers required 12 steps.

我所做的是这样的:

` #include <iostream>

using namespace std;



int necklace(){

    int firstNumber, secondNumber, total = 0, counter = 10, sumOfTwo, tempOne, tempTwo, count;



    // 2 single digit numbers
    // add first two numbers and save only one digit
    // process keeps going until original numbers are found

    cout << "Enter the first number: \n";
    cin >> firstNumber;
    cout << "Enter the second number: \n";
    cin >> secondNumber;

    sumOfTwo = firstNumber + secondNumber;
    while (sumOfTwo >= 10){
        sumOfTwo /= 10;
    }
    int numbersArray[] = {firstNumber, secondNumber, sumOfTwo};

    for(int i = 0; i <= 20; i++){


        tempOne = numbersArray[i + 1];
        tempTwo = numbersArray[i + 2];



        sumOfTwo = tempOne + tempTwo;
        while (sumOfTwo >= 10){
            sumOfTwo %= 10;
        }

        numbersArray[i + 3] = sumOfTwo;


        total++;

        if(tempOne == firstNumber && tempTwo == secondNumber){
            break;
        }


    }


    for(int i = 0; i < sizeof(numbersArray); i++){
        cout << numbersArray[i];
    }

    cout << endl << "It took " << total << " steps to finish. \n";

    return total;
}


int main() {

    necklace();


}


`

我遇到的问题是它会打印出除原始 2 之外的所有数字,例如,如果我使用带有 1 和 8 的示例,它会打印出 189763921347 然后崩溃,当它应该打印出 18976392134718,最后加上 1 和 8。有什么建议么?谢谢!

int numbersArray[] = {firstNumber, secondNumber, sumOfTwo};

右侧有三个元素使其成为大小为 3 的数组。意味着索引为 0、1 和 2。
使用更高的索引将导致未定义的行为 (UB)。

另一方面:

for(int i = 0; i <= 20; i++){

    tempOne = numbersArray[i + 1];
    tempTwo = numbersArray[i + 2];
    [...]
    numbersArray[i + 3] = sumOfTwo;

最后一行 i 最多 20 个(包括)索引这个完全相同的数组,从 0 到 23!

下一个:

for(int i = 0; i < sizeof(numbersArray); i++){

sizeof(numbersArray) returns 数组的大小字节

sizeof(numbersArray) = 3 * sizeof(int)

大于3,数组的实际大小。


但是,如果您打算打印值而不是存储它们,则不需要数组。您只需要 "exchange" 值,例如:

one two   // beginning of loop
  ___|
 |    __ new_digit
 |   |
 v   v
one two   // end of loop