河内
从您的代码中,我看不到您想如何解决问题。我认为,第 1 步对您来说是制定解决问题的方式,并在没有编程语言的情况下进行描述——可能是伪代码,或者是 Word 中的项目符号列表。然后,您可能会从那里开始使用编程语言进行编程。
C++
您的代码看起来有点像一些随机代码片段。让我们看看您是否可以更深入地了解这个基本的 C++ 代码片段。它并不是真正的特定问题,但它可能会让您开始真正的 C++ 程序。
//file: hanoi.cpp
// Tower of Hanoi
#include <iostream> //! std is without '.h', add a space after 'include'
//! '<stdlib.h>' only needed for C-ish; maybe later, and then use <cstdlib>
//! first try it without '#include <conio.h>', try using 'cout << "\r"' with numbers.
#include <assert.h> //! assert()
using std::cout; //! do this, or always writw `std::cout`
using std::cin;
using std::endl;
//! DECLARATION
class HanoiTowers
{
const size_t disks_; //! some people mark class fields with a ending '_'
public:
explicit HanoiTowers(size_t disks);
//! use 'size_t' for indexes into array
void move(int n, size_t srcpole, size_t sparepole, size_t dstpole);
};
//! IMPLEMENTATION
HanoiTowers::HanoiTowers(size_t disks)
: disks_(disks)
{
// ... more init code ...
}
void HanoiTowers::move(int n, size_t srcpole, size_t sparepole, size_t dstpole)
{
//! ... is your algorithm going to work? I dont know ...
if(n==1) {
// sparepole and dstpole are swapped
cout << "Move top disk from pole" << srcpole; //! ending ';' was missing
cout << "Move pole" << dstpole << endl;
} //! closing '}' was missing
else {
// ... any code what you need. I can not get your idea here ...
move(n-1,srcpole, sparepole, dstpole);
move(1, srcpole, dstpole, sparepole);
move(n-1, sparepole, dstpole, srcpole);
}
}
static const size_t HEIGHT = 6; //! use consts
//! I can not see the use of this data strucure for you problem. whats your idea?
class array
{
//! ok, its good to make stuff private, but then you need public accessors
private:
int t1[HEIGHT],t2[HEIGHT],t3[HEIGHT]; //! what do you want to store in these?
//! is it not enough to store that stack-heights for each stack?
int srcpole, sparepole, dstpole;
//! accessors:
public:
int getT1WithIndex(size_t idx) const {
assert(idx < HEIGHT); //! checks in code
return t1[idx];
}
//! ... more of this, if needed ...
};
//! MAIN
int main(int argc, const char* args[]) //! one 'main' to make a program runnable
{
// ... any program code ...
cout << "Enter The amount of disk from 1-6..." << endl;
int disks = 6; //! default
cin >> disks; //! let user enter a number
//! create a data structure
HanoiTowers hanoi(disks);
//! execute your algorithm
hanoi.move(0,0,0,0); //! ???
//! ...more...???
return 0; //! '0': program succeeded
}
g++ -o hanoi.x hanoi.cpp
例如在 Unix 上编译它。