C++ How do I use variables from one function to another? -
for record green in c++ , other programming language matter, if it's possible i'd happy if can answer in way can understand :)
i have been working on simple rock, paper, scissors game have 3 basic functions, 1 user, 1 bot, , 1 choose 1 wins game.
i know using system("cls")
isn't best way go, i'm not planning on using outside windows.
the final function results()
need use variables x
, brand
2 previous functions, can't seem find way this. , people explain anywhere else, explain advanced me. remeber don't need change of them, have compare them determine winner.
i'll show code here can see dealing with. please give me comments on other things can improve here.
#include <iostream> #include <stdlib.h> #include <time.h> #include <windows.h> using namespace std; int bgame(), ugame(), results(); int main() { srand(time(null)); cout<<"welcome rps!\n" <<"you know do.\n" <<"\n[enter]"; cin.ignore(); system("cls"); ugame(); return 0; } int ugame() { int x; cout<<"type number 1-3: "; cin>> x; cin.ignore(); if ( x == 1 ) { cout<<"\nyou chose rock!\n" <<"\n[enter]"; cin.ignore(); bgame(); } else if ( x == 2) { cout<<"\nyou chose paper!\n" <<"\n[enter]"; cin.ignore(); bgame(); } else if ( x == 3 ) { cout<<"\nyou chose scissors!\n" <<"\n[enter]"; cin.ignore(); bgame(); } else { cout<<"\ntry again.\n" <<"\n[enter]"; cin.ignore(); ugame(); system("cls"); } return 0; } int bgame() { int brand = rand()>>4; system("cls"); cout<<"the bot choose item.\n" <<"\n" <<"[enter]\n"; cin.ignore(); brand = rand() % 3 + 1; if ( brand == 1) { cout<<"\nbot chose rock!"; cin.ignore(); results(); } else if ( brand == 2 ) { cout<<"\nbot chose paper!"; cin.ignore(); results(); } else if ( brand == 3 ) { cout<<"\nbot chose scissors!"; cin.ignore(); results(); } else { cout<<"\nerror."; cin.ignore(); bgame(); system("cls"); } return 0; } int results() { }
you can send "parameters" function. that's create copy of variable , can use in function.
you need specifies function name (that's named prototype) :
int results(int x, int brand)
you put type name , variable name. example function take 2 int parameters.
int results(int x, int brand) { // variables }
and when call function type:
results(x, brand);
if want, link explains images , examples , more details: http://www.cplusplus.com/doc/tutorial/functions/
Comments
Post a Comment