打印出代码时,它会运行,但似乎不运行该coinflip()
功能.目前只试图打印出第一匹马串,随机前进.
#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
using namespace std;
string h0 = "0................";
string h1 = "1................";
string h2 = "2................";
string h3 = "3................";
string h4 = "4................";
int position0 = 0;
string coinflip0(string h0);
int main(){
cout << "Press Enter to begin! " <<endl;
cin.ignore();
std::cout << h0 << endl; //print string
cout << h1 << endl;
cout << h2 << endl;
cout << h3 << endl;
cout << h4 << endl;
// srand(time(NULL));//time goes back to zero for each loop
while(h0.at(16) != 0) {
cout << "\n Press Enter to continue " << endl;
cin.ignore();
string coinflip0(h0); // call function
cout << h0 << endl; //print new string
} //end while
} // end main
string coinflip0(string h0) {
// find random number(0 or 1)
int num = rand() % 2;
cout << num << endl;
position0 = position0 + num;
if(num==1){
std::swap(h0[position0], h0[position0+1]);
} // end if
return h0;
}//end coin flip
Run Code Online (Sandbox Code Playgroud)
输出:
Press Enter to begin!
0................
1................
2................
3................
4................
Press Enter to continue
0................
Press Enter to continue
0................
Press Enter to continue
0................
Press Enter to continue
Run Code Online (Sandbox Code Playgroud)
string coinflip0(h0); // call function
Run Code Online (Sandbox Code Playgroud)
这实际上不是函数调用.这是一个变量声明,类似于:
string coinflip0 = h0;
Run Code Online (Sandbox Code Playgroud)
要打电话给这个功能string
.一个简单的方法coinflip0(h0)
就可以了.我认为你想把结果分配回去h0
,所以也是这样做的:
h0 = coinflip0(h0);
Run Code Online (Sandbox Code Playgroud)