+ 1

[solved]Why the score function/method is not working in my program, please can anyone help me 😢

#include<iostream> #include<cstdlib> #include<ctime> using namespace std; int r_num1,r_num2,score=0,life=3; class ran{ public: void random() { r_num1=1+(rand()%6); r_num2=1+(rand()%6); } /*int life(){ public: life--; return life; }*/ void score(){ public: score+=1; } }; int main() { int ans,c_ans; srand(time(0)); ran o; while(true){ o.random(); c_ans=r_num1+r_num2; cout<<r_num1<<"+"<<r_num2<<"="<<endl; cin>>ans; if(ans==c_ans) { cout<<o.score()<<endl<<"score:"<<score<<endl; } } return 0; }

12th Nov 2021, 8:14 AM
Samaan Sayed
3 odpowiedzi
+ 3
Jayakrishna🇮🇳 thanks and your explanation is wonderful I understood everything 😌
12th Nov 2021, 10:15 AM
Samaan Sayed
+ 1
//Working code .. //but it may modified to better by taking class variable instead of global variables... You have infinite loop, make it to limited. //Read comments.. and reply if anything is not understandable.... #include<iostream> #include<cstdlib> #include<ctime> using namespace std; int r_num1,r_num2,score=0,life=3; class ran{ public: void random() { r_num1=1+(rand()%6); r_num2=1+(rand()%6); } /*int life(){ public: life--; return life; }*/ void rscore(){ //already used score as variable name so I changed function name.. //public: //its not valid here to put. score+=1; } }; int main() { int ans,c_ans; srand(time(0)); ran o; while(true){ o.random(); c_ans=r_num1+r_num2; cout<<r_num1<<"+"<<r_num2<<"="<<endl; cin>>ans; if(ans==c_ans) { o.rscore(); // it wont returning anything so just call like this cout<<"score:"<<score<<endl; } break;//to terminate loop, instead loop limited times by a counter variable. } return 0; }
12th Nov 2021, 10:02 AM
Jayakrishna 🇮🇳
+ 1
You're welcome..
12th Nov 2021, 10:21 AM
Jayakrishna 🇮🇳