程序崩溃,不显示正确的输出
Program crashes and does not display correct output
所以我正在为我的c ++类解决一个非常"基本"的问题,并遇到了一些错误。问题是这个
数论中一个有趣的问题有时被称为"项链问题"。此问题从两个个位数开始。下一个数字是通过将前两个数字相加并仅保存一位数字来获得的。重复此过程,直到"项链"通过返回到原来的两个数字关闭。例如,如果起始数字是 1 和 8,则需要十二个步骤才能关闭"项链": 18976392134718 编写一个程序,要求用户输入两个起始编号,然后显示顺序和所执行步骤数。程序输出应类似于: 输入第一个数字:1 输入第二个数字:8 18976392134718 您的数字需要 12 个步骤。
我所做的是这样的:
` #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 然后崩溃,当它应该打印出带有 1 和 8 的18976392134718时。有什么建议吗?谢谢!
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)
返回数组的大小(以字节为单位):
sizeof(numbersArray) = 3 * sizeof(int)
大于 3,数组的实际大小。
但是,如果您打算打印值但不存储它们,则不需要数组。您只需要"交换"这样的值:
one two // beginning of loop
___|
| __ new_digit
| |
v v
one two // end of loop
相关文章:
- 了解 Linux 虚拟内存:valgrind 的 massif 输出显示了有和没有 --pages-as-heap 的主要差异
- 输出显示多个带整数的字符串值
- 如何使代码的输出显示为"工资减税"
- 如何让我的输出显示输入金额的星号
- 控制台输出显示ASCII值,而不是数字的预期数字
- 如何修复输出显示,以便显示正确排序的数据
- Android Studio 3.2:cmake message()输出显示在哪里
- 如何将OpenCV的输出显示或流式传输到HTML页面或其他一些客户端应用程序
- 我写了一个函数来删除循环链接列表中的第 1 个节点,但输出显示无限次"55 44 33 22 11 99",那么我该如何解决呢?
- 从c++程序运行shell脚本会自动将shell脚本的输出显示到控制台吗
- 为什么我的输出显示显示计算器中的每个选项
- C++将输出显示到php中
- 从 PHP 调用 C++ 应用程序 - 输出显示"Array"
- 有没有办法C++让循环的输出显示在同一行上
- 为什么日志输出显示在控制台主机中,而不显示在ISE中?(v4.0)
- 如何让GDB为每一行输出显示时间戳
- 为什么输出显示为无符号数
- 如何获得gdb tui汇编输出显示指令
- 为什么输出显示错误
- FFTW输入输出显示DSP