我是 C 的新手,正在研究河內專案的遞回塔。除了一個小錯誤,我已經完全完成了。“cout <<“移動次數” << count; 中的第二個 << 給了我錯誤“沒有運算子“<<”匹配這些運算元”。我知道它與計數有關,但我不確定如何修復它。
編輯:同一行也有這個錯誤 Error C2679 binary '<<': no operator found which requires a right-hand operation of type 'overloaded-function'
代碼:
#pragma warning(disable: 4996)
#include<string>
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<cmath>
using namespace std;
void toh(int p, char from, char to, char a){
static int count = 0;
if (p == 0) {
return;
} //if end
if (p == 1) {
cout << "from " << from << " to " << to << endl;
count ;
return;
} //if end
toh(p - 1, from, a, to);
cout << "from " << from << " to " << to << endl;
count ;
toh(p - 1, a, to, from);
} //toh end
int main() {
int num; bool t = 1;
do {
cout << "Enter the No. of the disks : ";
cin >> num;
cout << "source 1 target 2 temporary 3" << endl;
toh(num, '1', '2', '3');
cout << "2 to the " << num << " power = " << pow(2, num) << endl;
cout << "Number of moves " << count;
cout << "Continue? (1=yes 0=no) : ";
cin >> t;
} while (t);
system("pause");
return 0;
} //main end
uj5u.com熱心網友回復:
該變數count是在函式的區域定義的toh,因此您可以回傳count可以分配給count內部呼叫的變數的值main,從而允許您在行中使用它cout << "Number of moves " << count;。它應該是這樣的:
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<cmath>
using namespace std;
static int toh(int p, char from, char to, char a){
static int count = 0;
if (p == 0) {
return count;
} //if end
if (p == 1) {
cout << "from " << from << " to " << to << endl;
count ;
return count;
} //if end
toh(p - 1, from, a, to);
cout << "from " << from << " to " << to << endl;
count ;
toh(p - 1, a, to, from);
} //toh end
int main() {
int num, count; bool t = 1;
do {
cout << "Enter the No. of the disks : ";
cin >> num;
cout << "source 1 target 2 temporary 3" << endl;
count = toh(num, '1', '2', '3');
cout << "2 to the " << num << " power = " << pow(2, num) << endl;
cout << "Number of moves " << count;
cout << "Continue? (1=yes 0=no) : ";
cin >> t;
} while (t);
system("pause");
return 0;
} //main end
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341800.html
標籤:C
下一篇:C 轉發不是右值參考的可變引數值
