Feb 8, 2017 at 4:40am UTC
I can't get the variable netval to add the val variable after each for loop. As it is, the output of this is simply the last value I input into the program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include <iostream>
using namespace std;
int main(){
int cardnum,val, netval, counter;
char cards;
cout << "How many cards? " ;
cin >> cardnum;
cout <<"Input the value of your cards: " ;
for (counter = 0; counter < cardnum; counter++){
cin >> cards;
switch (cards)
{
case '2' :
val = 2;
break ;
case '3' :
val = 3;
break ;
case '4' :
val = 4;
break ;
case '5' :
val = 5;
break ;
case '6' :
val = 6;
break ;
case '7' :
val = 7;
break ;
case '8' :
val = 8;
break ;
case '9' :
val = 9;
break ;
case 't' :
val = 10;
break ;
case 'j' :
val = 10;
break ;
case 'q' :
val = 10;
break ;
case 'k' :
val = 10;
break ;
case 'a' :
val = 1;
break ;
default :
cout << "Enter a valid character." ;
break ;
}
netval =+ val;
}
cout << netval;
return 0;
}
Last edited on Feb 8, 2017 at 4:44am UTC
Feb 8, 2017 at 4:51am UTC
@conzerban
netval =+ val
The above is written incorrectly. It should be..
netval += val
Feb 8, 2017 at 5:07am UTC
Thanks. Though that gives me a very large number.
Feb 8, 2017 at 5:32am UTC
@conzerban
You might want to initialize netval as 0, to begin with, otherwise, who knows what the value starts with when you start adding val to it.
Feb 8, 2017 at 5:42am UTC
That was it! Thanks for the help.
Feb 8, 2017 at 5:46am UTC
You're welcome, conzerban..
Feb 8, 2017 at 5:47am UTC
> Though that gives me a very large number.
Initialise
netval
Tip: turn on all compiler warnings (it would have alerted you about the use of an uninitialised variable)
Tip: postpone the declaration of local variables to as late as possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
int main() {
int cardnum ;
std::cout << "How many cards? " ;
std::cin >> cardnum;
int netval = 0 ; // initialised with zero
std::cout <<"Input the value of your cards: " ;
for ( int counter = 0; counter < cardnum; ++counter ) {
char card ;
std::cin >> card;
int value = 0 ; // initialised with zero
if ( card >= '2' && card <= '9' ) value = card - '0' ; // '3' - '0' == 3 etc.
else switch (card) {
case 't' : case 'T' : value = 10 ; break ;
case 'j' : case 'J' : value = 11 ; break ;
case 'q' : case 'Q' : value = 12 ; break ;
case 'k' : case 'K' : value = 13 ; break ;
case 'a' : case 'A' : value = 1 ; break ;
default : std::cout << "invalid card '" << card << "' is ignored\n" ;
}
netval += value; // note: value remains zero for invalid input
}
std::cout << "net value: " << netval;
}
Last edited on Feb 8, 2017 at 5:49am UTC