新人又來了,我又像往常一樣卡住了。 (不知道我的問題標題應該是什麼,但它的功能絕對相關,我認爲)我想讓用戶擲出骰子,並在達到20時將其最大化。但是,這是我的功能obj.currentRoll();
並沒有疊加上一卷正如我打算的那樣。基本上我想要它存儲價值value=value+roll;
連續轉動,以便以後我可以使用if語句,如if (value>max){return 0}
或這樣的。我能夠以更簡單的方式做到這一點,而無需使用單獨的課程或功能,但我希望以這種方式獲得相同的結果並且失敗。有什麼建議麼?在我的程序中使用基本類功能。 C++
#include <iostream>
#include "myClass.h"
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
std::string rollCh;
const int max=20;
std::cout<<"Your lucky number for the day is " <<1+(rand()%30)<<"\n";
std::cout<<"Roll the dice? (Y/N)"<< "\n";
std::string ch;
std::cin>>ch;
if(ch=="Y"||ch=="y"){
myClass obj;
do
{
std::cout<<"Rolling...\n"<<"\n";
std::cout<<"You rolled "; obj.funcRoll();std::cout<<"!!!" <<"\n";
std::cout<<"Double checking your roll...yes it is ";obj.funcRoll();
obj.currentRoll();
std::cout<<"\n\n Roll again? (Y/N)"<<"\n";
std::cin>>rollCh;
}
while (rollCh=="Y"||rollCh=="y");
}
return 0;
}
myClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class myClass
{
public:
myClass();
void funcRoll();
int roll;
int value;
void currentRoll();
};
#endif // MYCLASS_H
myClass.cpp
#include "myClass.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
myClass::myClass()
{}
void myClass:: funcRoll(){
srand(time(0));
roll=1+(rand()%6);
std::cout<<roll;
}
void myClass:: currentRoll(){
value=0;
value=value+roll;
std::cout<<"\n You have rolled "<< value<<" so far";
}
,我做到了第一
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
int max=20;
int value=0;
int roll;
std::string ch;
do
{
srand(time(0));
roll=1+(rand()%6);
std::cout<<"\nYou rolled "<<roll<<"\n";
value=value+roll;
std::cout<<"Your total value = " << value<<"\n";
if (value<max){
std::cout<<"continue? \n\n"<<"\n";
std::cin>>ch;}
else {
std::cout<<"You have maxed out. Congrats!"<<"\n";
return 0;
}
}
while (ch=="y"||ch=="Y");
return 0;
}
在您的currentRoll()函數中,您每次都將值設置爲「0」。而是使用類構造函數將其設置爲「0」。 – Ron
我在公開場合嘗試設置值= 0之前,但得到了一些錯誤,我認爲 – Sanrai
Offish topic:'srand(time(0));'最好叫一次。它重置隨機數生成器,如果每秒鐘調用一次(「時間」的分辨率),則生成器將被重置爲相同的種子並生成相同的隨機序列。可見的結果是一遍又一遍生成的相同編號的樂隊。 – user4581301