Trying to get a variable equal to other variables in C - c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int score=0;
int loop=0;
int randNUM1=0;
char randSYMB1=0;
int randNUM2=0;
int correct_answer=0;
int answer=0;
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10; printf("%c", "0123456789"[randNUM1]);
randSYMB1 = rand()%4; printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10; printf("%c\n", "0123456789"[randNUM2]);
printf("What is your answer?");
scanf("%d", &answer);
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
if (randSYMB1=="/")
{
printf("The correct answer is %d\n", randNUM1/randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="*")
{
printf("The correct answer is %d\n", randNUM1*randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="+")
{
printf("The correct answer is %d\n", randNUM1+randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="-")
{
printf("The correct answer is %d\n", randNUM1-randNUM2);
scanf("%d", &correct_answer);
score++;
}
printf("Your score is %d\n", score);
}
}
The code is for a simple calculation game, in which the user is asked 10 questions, which consist of randomly generating a number, then a symbol then another number, the answer is then stored, and then the user is told whether their answer was correct, and at the end of the 10 questions the user is given a score out of 10. My code seems to generate the numbers and the symbols randomly, and loops for 10 questions, but however, the code does not seem to take the IF statements into account, which then means that the correct answer isn't displayed, and thereofre, the score output to the user after every question is 0. Therefore, from what I can teel there is a problem with the IF statements, but I can't understand, what that problem is. I have also tried to use CASE statements instead, but the problem is still the same; the statements are not taken into account by the program. I cannot understand why the program does this. Is it a problem in the FOR loop, or is the probelm with the problem with the "correct_answer" variable? Please help!

Benny, much of the difficulty you are having just stems from apparently just starting in coding. There is nothing wrong with that, if you knew it all already, then you wouldn't need to learn... (and you are never really done learning how to program, hardware changes, standards change, etc.. It's a journey not a race)
First, if you have the option, declare all variables before you begin executing statements. This will keep your code portable to compilers still using the C89 standard (all windoze versions through Win7), e.g.
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL)); /* now begin executing statements */
It's a matter of style, but if you open the spacing up a bit, it will make your code more readable (especially for older eyes...). While you can save lines by cramming two expressions on each line or using the comma operator -- don't. It just makes your code harder to read (for you and anyone else). Sure, if it is stupid-short, then you can get away with it, e.g.
if (!a) b = 1;
otherwise, put each statement on it's own line:
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
Next, the crux of your issues are how to handle the logic of checking the math operation and the user's answer. All of the logic is based on what random character was generated with randSYMB1 = symbol[rand() % 4]; (my changes).
How do you take different actions based on a what one of a set of characters could be? Well, you can daisy-chain a whole string of if and else if statements together, or, just use a switch statement:
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
That leaves your a single simple comparison to determine if the correct answer was entered:
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
(note: for division, the user must enter the result of what integer division would produce)
Putting it altogether, you could boil your code down to:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void) {
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL));
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
}
return 0;
}
Example Use/Output
C:\Users\david\Documents\dev\src-c\tmp>bin\mathtest.exe
9 + 3
What is your answer?: 12
Correct!
Your current score is: 1
8 * 8
What is your answer?: 64
Correct!
Your current score is: 2
5 + 7
What is your answer?: 12
Correct!
Your current score is: 3
6 - 4
What is your answer?: 2
Correct!
Your current score is: 4
6 / 4
What is your answer?: 1
Correct!
Your current score is: 5
7 * 9
What is your answer?: 63
Correct!
Your current score is: 6
5 / 6
What is your answer?: 0
Correct!
Your current score is: 7
8 * 2
What is your answer?: 16
Correct!
Your current score is: 8
0 / 1
What is your answer?: 0
Correct!
Your current score is: 9
9 + 7
What is your answer?: 16
Correct!
Your current score is: 10
Look things over and let me know if you have further questions.

There are several problems with your code. randSYMB1 will have a value of 0 to 3, none of which corresponds to the ascii values of /*+-.
Change the if statements to:
if (randSYMB1==0)
and accordingly to the rest. Also, you should never write something like:
char c;
...
if(c == "x")
You should use single quotes:
if(c == 'x')
This line:
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
is complete jibberish. Move the calculation of correct value inside the if statements.
This:
printf("%c", "0123456789"[randNUM1]);
works, but it's pretty insane. This is better:
printf("%d", randNUM1);
I guess it's ok as a quick workaround for randSYMB1 but there's no reason at all with the operands.
Here is a working version of the for loop:
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10;
printf("%d", randNUM1);
randSYMB1 = rand()%4;
printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10;
printf("%d\n", randNUM2);
printf("What is your answer?");
scanf("%d", &answer);
if (randSYMB1==0)
correct_answer=randNUM1/randNUM2;
else if (randSYMB1==1)
correct_answer=randNUM1*randNUM2;
else if (randSYMB1==2)
correct_answer=randNUM1+randNUM2;
else if (randSYMB1==3)
correct_answer=randNUM1-randNUM2;
printf("The correct answer is %d\n", correct_answer);
if(answer == correct_answer)
score++;
printf("Your score is %d\n", score);
}

If never executes because randSYMB1 is number between 0-3, and not "/*-+". Also i suggest seeding random first, but in this case it doesn't matter.

Related

A question about break statement in c programming

I wrote this loop to add numbers, and the break to get out of the loop if the number entered is less than zero, and in last print the calculated numbers without adding the negative number. but the problem is even I wrote the break statement before the addition when I enter 15 and 15 and -2 the output is 28 rather than 30
I found out how to fix that, what I want to know is why
and thank you.
#include <stdio.h>
void main()
{
int j = 1, num = 0, rslt = 0;
while (1) {
if (num < 0) break;
printf("enter a number : ");
scanf("%d", &num);
rslt = rslt + num;
}
printf("the resluts are %d\n", rslt);
}
Currently, you are effectively testing the input of the previous iteration, after already adding it to your result. Instead, check the number immediately after the user enters it, before you perform any calculations.
#include <stdio.h>
int main(void)
{
int num = 0, rslt = 0;
while (1) {
printf("enter a number : ");
scanf("%d", &num);
if (num < 0)
break;
rslt += num;
}
printf("the results are %d\n", rslt);
}
You might also want to check that scanf returns the number of successful conversions you were expecting (in this case one), to handle the event where the user enters invalid input.
if (1 != scanf("%d", &num))
break;

How to debug a C program producing unexpected output?

I am new to programming C and I don't know why my program is not printing the desired output.
#include <stdio.h>
void main(void)
{
char res,res1;
float money=10;
printf("***Wealcome to Peace of Mind***");
printf("\nHello we have the menu please check::");
printf("\n***MenĂº***");
printf("\n");
printf("\n<<<Bebidas>>>");
printf("\n 1 - Coca-Cola = 1,5 2 - IceTea = 1,4");
printf("\n 3 - Super Bock = 1,70 4 - Sumol = 1,6");
printf("\n");
scanf("%d",&res);
switch(res)
{
case 1 || 'Coca-Cola':money - CocaCola;break;
}
printf("%.1f",money);
//Is that result i want:
printf("\n%.1f",10-1.5);
}
Output of my program:
The syntax of your case statement is not correct. Also the code is using scanf() to read an integer, but storing the integer-sized value in a char.
I tidied up the code:
#include <stdio.h>
int main(void)
{
int res;
float cost = 0;
float money = 10;
printf("***Wealcome to Peace of Mind***\n");
printf("Hello we have the menu please check::\n");
printf("***MenĂº***\n");
printf("\n");
printf("<<<Bebidas>>>\n");
printf(" 1 - Coca-Cola = 1,5 2 - IceTea = 1,4\n");
printf(" 3 - Super Bock = 1,70 4 - Sumol = 1,6\n");
printf("\n");
scanf("%d", &res);
switch(res)
{
case 1:
cost = 1.5;
break;
case 2:
cost = 1.4;
break;
// TODO: case 3 & 4
default:
printf("Invalid Entry\n");
cost = 0;
}
printf("money = %.1f\n", money - cost);
return 0;
}
Some further notes:
As commentators pointed out, put \n at the end of the string
When you compile, turn on warnings, and try to fix all of them.
In case blocks, it's good practice to have a default to catch errors
It would be worthwhile to store the drink prices as #define constants (or as an array of values, or some common area so the value is only set once in the program, and everything else just references that.)
#define COLA_COST 1.5

Why is this for loop getting ignored? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what i'm doing wrong but the for loop is not initializing
The code just goes immediately to displaying the printfs. That have no values in them since the for loop didn't activate
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("Pause")
main() {
// INITALIZE VARIABLES
int number = 0;
int i = 0;
int odd = 0;
int even = 0;
int totalNum = 0;
int tempNum = 0;
int count;
printf("Enter a number between 2 and 25\n");
scanf("%i", &number);
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
for (i = 1; i == count; ++i){
printf("input numbers\n");
scanf("%i", &tempNum);
if (tempNum % 2 == 0)
even++;
else
odd++;
totalNum = totalNum + tempNum;
} // END FOR LOOP
// DISPLAY OUTPUT
printf("You entered %i numbers\n", count);
printf("The sum of the %i numbers is %i\n", count, totalNum);
printf("The average of the %i numbers is %i\n", count, totalNum / count);
printf("You entered %i odd numbers and %i even numbers\n", odd, even);
PAUSE;
} // END MAIN
Your loop will only execute at best once, when count == 1 as you initialize i to 1.
If you enter a 1 for count,
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
the loop will run exactly once, until i increments to 2
You probably want:
for (i = 1; i <= count; ++i){
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
it should be...
do{
if (number < 2 || number > 25){
printf("That was an invalid number please try again\n");
scanf("%i", &number);
}
} while (number < 2 || number > 25);
else it asks always another number
i = 1, so i == count; gives false therefore the loop is ignored.
A for loop in C works like this:
for ( variable initialization; condition; variable update ) {
/* Do something... */
}
The loop will execute for as long as condition is true. So, when you do:
for (i = 1; i == count; ++i)
The loop will execute for as long as i == count is true. So, unless count holds 1 when this line is executed, the loop will never run.
As others pointed out, you probably want this:
for (i = 1; i <= count; ++i)
So your loop will run for all values of i, until it reaches count.
As a side note i should point out that the usual way to write for loops in C is something like this:
for (i = 0; i < count; i++)
We start with i = 0 because C arrays are zero-based, so the Nth element of an array has index n-1
You were so close. In addition to fixing your loop test clause for (i = 1; i <= count; i++), I would suggest using " %d" for your format specifier. Your do loop need only be a while loop to avoid printing your invalid number message every time.
Additionally, While not an error, the standard coding style for C avoids caMelCase variables in favor of all lower-case. See e.g. NASA - C Style Guide, 1994.
With those changes, (and changing your odd/even check to a simple &) you could write your code as follows.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// #define PAUSE system("Pause")
int main (void)
{
int number, i, odd, even, totalnum, tempnum, count;
number = i = odd = even = totalnum = tempnum = count = 0;
printf ("enter a number between 2 and 25: ");
scanf (" %d", &number);
while (number < 2 || number > 25) {
printf ("invalid number, again (between 2 and 25): ");
scanf (" %d", &number);
}
printf ("numbers to input: ");
scanf (" %d", &count);
for (i = 1; i <= count; i++) {
printf ("input number %2d: ", i);
scanf (" %d", &tempnum);
if ((tempnum & 1) == 0)
even++;
else
odd++;
totalnum = totalnum + tempnum;
}
printf ("You entered %d numbers\n", count);
printf ("The sum of the %d numbers is %d\n",
count, totalnum);
printf ("The average of the %d numbers is %d\n",
count, totalnum / count);
printf ("You entered %d odd numbers and %d even numbers\n",
odd, even);
// PAUSE;
return 0;
}
note: main is type int (e.g. int main (int argc, char **argv) or simply int main (void) to indicate no arguments taken). Since it is type int it will return a value to the shell. While historic implementations may have allowed void main that is no longer the case for portable code.
Example Use/Output
$ /bin/forskipped
enter a number between 2 and 25: 4
numbers to input: 4
input number 1: 1
input number 2: 2
input number 3: 3
input number 4: 4
You entered 4 numbers
The sum of the 4 numbers is 10
The average of the 4 numbers is 2
You entered 2 odd numbers and 2 even numbers
Look it over and let me know if you have any questions.

random numbers in c inside a loop

I'm learning C and find rand() very strange:
I've the following game:
I have played the game several times and the correct answer was something near 47.
For example:
between 1 and 100 it would be 47
between 1 and 500 it would be 247 or 347.
between 1 and 1000 it would be 347.
I don't want the number to be easily guessed after the third time.
Is there any problem? how can I modify this code to do the job?
#include<stdio.h>
#include<stdlib.h>
void main()
{int n,l,c,tries;
char yn;
first:
n=0,c=0,l=0,tries=0;
do{
printf(" 1: Easy\n 2:Medium\n 3:hard\n");
scanf("%d",&l);
}while(l<1 || l>3);
switch(l)
{
case 1:
n = rand % 100 +1;
printf("I picked a number between 1 and 100\n");
break;
case 2:
n = rand()%500 + 1;
printf("I picked a number between 1 and 500\n");
break;
case 3:
n = rand()%1000 + 1;
printf("I picked a number between 1 and 1000\n");
break;
}
do
{
tries++;
printf("Enter your guess: \t");
scanf("%d",&c);
if(c == n)
printf("You Won\n number of gusses= %d\n", tries);
else
{
if(c > n)
printf("High\n");
else
printf("Low\n");
}
}while(c !=n);
printf("Try Again \?(Y/N)\n");
scanf(" %c",&yn);
if(yn == 'Y' || yn == 'y')
goto first;
}
If you reboot your pc you'll see that the results will be different.
Random is not clever as you expect, and, to tell you the truth, is not properly random! (:
By the way, to provide a different seed to the random alghoritm, you have to call, only one time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
srand(time(0));
Take a look to the documentation!
edit
To improve your code:
int randN = 100;
switch (l) {
case 1:
break;
case 2:
randN = 500;
break;
case 3:
randN= 1000;
break;
default:
randN = rand() % 1000 + 1;
break;
}
n = rand() % randN + 1;
printf("I picked a number between 1 and %i.\n", randN);
use srand and then use rand i.e
int main()
{
srand(time(0)); // use current time as seed for random generator
int random_variable = rand();
printf("Random Value= %d",random_variable);
return 0;
}

Number Guessing Game with two players

Can someone please help me figure out what is wrong with my program it is prety complex for me. It is a number guessing game where two player can play. It starts by saying which player goes first and the player then has to input his number either 1 or 2 and then enter a guess or either pass (players can't pass more than 3 times or twice in a row). It is working very good except that everytime player 1 starts it asks him for a guess twice in a row bu then works fine, and when player 2 starts it alternates like it should like this:
And this is my code It quite a lot of code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;
srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", playerNumber);
printf("Player Number?\n");
scanf("%d", &playerInput);
while (playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (playerA != playerNumber)
playerB = playerNumber;
if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");
else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First of all, you should use consistent indentation. That will make it easier to read your code.
Second, you should use newlines and whitespace to group like-lines together. Think of writing code like writing prose, and newlines as ways to separate paragraphs. You don't double-space almost anything, because it wastes space and is harder to read (people aren't used to it) so don't double-space your code.
Third, your use of the playerA and playerB variables is an OK concept, but there are better ways to do it. The typical convention in C/C++ is to use a #define for magic numbers, with all caps - #define PLAYER_A 1. Following this convention will make your code more readable. Also, since your players are "1" and "2" it is more readable to use #define PLAYER1 1 or PLAYER_1.
You use the variable "i" but the convention for using variables named i, j, k, m, or n is as loop counters that are incremented either at the top of the loop or at the bottom of the loop. Incrementing the loop counter in the middle of the loop makes it much easier for the counter to get lost. Move the increment to the top or the bottom.
Do the work by hand to see what your variables are as the program executes. Your teacher has done this in class. Just write down each variable and write its value next to it, then change the variables as they will change while the program executes. This technique will help you fix other difficult bugs in the future, rather than me giving you the answer.
You have an infinite loop in your code,
your code given below is wrong,
while(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
It should be,
if(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}

Resources