【发布时间】:2021-11-27 04:04:17
【问题描述】:
问候堆栈溢出,最近遇到了一个问题,即我的代码没有完全按照我的意图执行。我的意图是让用户输入一个数字,然后程序将检查它的素因子,当它找到一个素因子时,我希望它把数字推入堆栈。我尝试在整个程序中放置 cout 语句,以查看是否有任何特定位置不起作用,但我还没有找到任何东西。我相信我已经非常接近解决这个问题了,但我不确定如何从这里开始。
这是我的代码:
#include <iostream>
#include <cmath>
using namespace std;
class stack
{
public:
static const int MAX = 100;
stack() { used = 0; } // constructor
void push(int entry);
int pop();
int size() { return used; }
bool empty() { return used == 0;}
private:
int data[MAX];
int used; // how many elements are used in the stack, top element is used - 1
};
void stack::push(int entry)
{
data[used] = entry;
++used;
}
int stack::pop()
{
--used;
return data[used];
}
void primeFactors(stack, int);
int main()
{
stack primeValues;
int entry = 0;
cout << "Enter a positive integer (0 to stop): ";
cin >> entry;
if (entry != 0)
{
cout << "Prime factors: " << entry << " = ";
}
primeFactors(primeValues, entry);
while(primeValues.pop() != 0) // hopefully continues to pop the prime factors until it reaches zero?
{
cout << primeValues.pop() << " ";
}
return 0;
}
void primeFactors(stack primeValues, int entry)
{
if (entry == 0)
{
return; // terminate when zero is reached
}
if (entry == 1)
{
cout << entry; // if 1 is reached display one
}
while (entry % 2 == 0) // while there is no remainder do the following
{
primeValues.push(2); // push two into stack
entry = entry/2;
}
for (int i = 3; i <= sqrt(entry); i = i+2) // start looping through numbers to find more prime factors
{
while (entry % i == 0)
{
primeValues.push(i);
entry = entry/i;
}
}
if (entry > 2) // if the number is greater than two and doesnt have prime factors push the number
{
primeValues.push(entry);
}
}
我尝试了各种不同的数字,但似乎没有任何效果。我已经尝试弹出几次以查看是否有任何东西被推送,但它只显示为零。我在这里错过了什么?
【问题讨论】:
-
出于好奇,有什么理由实现自己的堆栈,而不仅仅是使用
std::stack? -
这是一项学校作业,因此标准非常具体。我们实际上也没有被告知 std::stack 是一个东西。
-
在您的
push成员函数中,您可能应该检查以确保堆栈未“满”。 -
考虑学习如何使用调试器而不是“我已经尝试在整个程序中放置 cout 语句”,它肯定会节省您的时间,并且您将能够看到数据的变化。一个声明到下一个。如果一个程序给出了你期望的最终结果,并不一定意味着它可以正常工作。
标签: c++ stack prime-factoring