random numbers in c inside a loop - c

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;
}

Related

C code Calculations not outputting correctly after adding exit for program

Hey guys n gals first time poster first time learning code.
I am sure I am missing something very small that comes naturally when you stare at code long enough. Why are my calculations not working? what am I missing ?
I can get it working without implelemting the # exit but im sure im missing something here.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input;
int a,b,c;
while(1) {
printf("\nPlease Enter Temperature in kelvin \n\nThen enter # when you have had enough:\n ");
scanf(" %c", &input);
if(input == '#'){
break;
}
if(input != '#') {
scanf("%d",&c);
printf("\n1.Convert to celcius\n2.Convert to fahrenheit\nEnter choice now\n");
scanf("%d",&a);
switch(a) {
case 1:
b=(c-273);
printf("Temperature in celcius is %d\n\n",b);
break;
case 2:
b=((c*9)/5)-460;
printf("Temperature in fahrenheit is %d\n\n",b);
break;
default:
printf("You selected wrong choice");
break; /// End of code here
}
}
getchar ();
}
return 0;
}
the following proposed code:
appropriately horizontal spaced
appropriately vertically spaced
includes the suggested changes from the comments to the question
displays how to cleanly display menu
displays how to honor the right margin (column 72 or 80)
replaces 'magic' numbers with meaningful names
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#define CONVERT_KEVIN_TO_CELCIUS 273
#define OFFSET_KEVIN_TO_FAREN 460
int main( void )
{
char input;
int a,b,c;
while(1)
{
printf("%s",
"\nPlease Enter Temperature in kelvin"
"\n\nThen enter # when you have had enough:\n");
scanf(" %c", &input);
if(input == '#')
{
break;
}
ungetc( c, stdin );
scanf("%d",&c);
printf("%s",
"\n1.Convert to celcius"
"\n2.Convert to fahrenheit"
"\nEnter choice now\n");
scanf("%d",&a);
switch(a)
{
case 1:
b=(c-CONVERT_KEVIN_TO_CELCIUS);
printf("Temperature in celcius is %d\n\n",b);
break;
case 2:
b=((c*9)/5)-OFFSET_KEVIN_TO_FAREN;
printf("Temperature in fahrenheit is %d\n\n",b);
break;
default:
printf("You selected wrong choice");
break;
}
}
getchar ();
return 0;
}
Why are my calculations not working?
Code has various technical problem well addressed elsewhere.
Thought I'd mention some numeric issues.
To convert K to °F:
°C = 0K − 273.15
°F = °C×9/5 + 32
To do so with integer math and get the best answer
// (K − 273.15)×9/5 + 32
// (K*100 − 27315)×9/(5*100) + 32
// ((K*100 − 27315)×9 + 32×500)/500
// ((K*100 − 27315)×18 + 32×1000)/1000
// above using real math, below using integer C math
// t = (K*100 − 27315)×18 + 32×1000; (t + signof(t)*500)/1000
// More simplifications possible
int t = (K*100 - 27315) * 18 + 32*1000;
t += (t < 0) ? -500 : 500; // round by adding half the divisor, correctly signed
F = t/1000;
To do so with FP math and get a good integer answer
#include <math.h>
F = lround((K − 273.15)*9.0/5.0 + 32);

Guess a number game , How to add or display number of guesses left using while loop

Number guessing game which a user guess a number from 0-20 and i want it to display how many tries are left for the user for example the maximum tries is 5 and if the user got it wrong on the first try it will display something like "tries left : 4", how do i implement that in my code?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
time_t t;
srand((unsigned)time(&t));
int randomNumber = rand() % 21;
int num;
int guess = 0;
printf("\nThis is a guessing game.");
printf("\nGuess 5 times only\n");
printf("\nEnter your guess:");
scanf("%d",&num);
while (num != randomNumber && guess < 5){ //checks if num is equal or not to randomnumber and count is less than 5 or limit 5
if(num > randomNumber){ // checks if num is greater than randomNumber
printf("Too high! try again:");
scanf("%d",&num);
guess++;
}
if(num < randomNumber){ //checks if num is less than randomNumber
printf("Too low! try again:");
scanf("%d",&num);
guess++;
}
if(num == randomNumber){ //checks if num is equal to randomNumber
printf("You got it right!\n");
return 0;
}
if(guess == 5) //checks if tries is 5 then exits program.
{
printf("your out guess of guesses!\n");
return 0;
}
}
return 0;
}
You can add this inside your while loop (at the end)
// For total no of guesses = 5, if that is n then n - 1 - guess
printf("tries left %d\n", 4 - guess);
If you’re trying to print a value in a loop something along the lines of printf(“You have %d guesses left\n”,5-guess); might work
You already have an answer, but I would advise you using symbolic constants #define GUESS_NUM 4 instead of actual numbers in your statements and your program in general, in programs like this it makes no difference, but you can get confused very easily in larger projects.
Also, your loop should end when guess reaches 4 because you already have one guess before the loop. You could write something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define GUESS_NUM 4
int main()
{
time_t t;
srand((unsigned)time(&t));
int randomNumber = rand() % 21;
int num;
int guess = 0;
printf("\nThis is a guessing game.");
printf("\nGuess 5 times only\n");
printf("\nEnter your guess:");
scanf("%d",&num);
while (num != randomNumber && guess < GUESS_NUM){ //checks if num is equal or not to randomnumber and count is less than 5 or limit 5
if(num > randomNumber){ // checks if num is greater than randomNumber
printf("tries left : %d\n", GUESS_NUM-guess);
printf("Too high! try again:");
scanf("%d",&num);
guess++;
}
if(num < randomNumber){ //checks if num is less than randomNumber
printf("tries left : %d\n", GUESS_NUM-guess);
printf("Too low! try again:");
scanf("%d",&num);
guess++;
}
if(num == randomNumber){ //checks if num is equal to randomNumber
printf("You got it right!\n");
return 0;
}
if(guess == GUESS_NUM) //checks if tries is 5 then exits program.
{
printf("your out guess of guesses!\n");
return 0;
}
}
return 0;
}

Trying to get a variable equal to other variables in 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.

Printing all the armstrong numbers between 1 - 999 in c

If i want the output like:
1st Armstrong number = 0
2nd Armstrong number = 1
3rd Armstrong number = 153
.............................................
.............................................
20th Armstrong number = ....
here my question is : if i have to print many armstrong numbers(1st to 20th) then is it the proper way to write printf one by one ? then i need to much time & code will be so long,how i minimize it?
please help....
This is my code which is able to find first 6 Armstrong Number..
int main(){
int a, b, c, num, i=0,j=0;
printf("Printing all the armstrong numbers between 1 - 999");
while(i<=999)
{
a= i/100;
a= a*a*a;
num= i%100;
b= num/10;
b= b*b*b;
c= num%10;
c=c*c*c;
if(i==a+b+c)
{
j++;
if(j==1) printf("\n1st");
else if(j==2) printf("\n2nd");
else if(j==3) printf("\n3rd");
else if(j==4) printf("\n4th");
else if(j==5) printf("\n5th");
else if(j==6) printf("\n6th");
printf(" Armstrong number= %d",i);
}
i++;
} // end of while
return 0;
} // end of main
It's simple :
if(i==a+b+c)
{
j++;
int key = j % 10;
if(j == 11)
key = 11;
switch(key){
case 1:
printf("\n%dst Armstrong number= %d",j,i);
break;
case 2:
printf("\n%dnd Armstrong number= %d",j,i);
break;
case 3:
printf("\n%drd Armstrong number= %d",j,i);
break;
case 11:
default:
printf("\n%dth Armstrong number= %d",j,i);
}
}
It appears that the rule for ordinal numbers is as follows:
x % 10 == 1: *st
x % 10 == 2: *nd
x % 10 == 3: *rd
Otherwise: *th
Let's write this up in code:
const char * format =
(x % 10 == 1) ? "%dst armstrong number: %d\n" :
(x % 10 == 2) ? "%dnd armstrong number: %d\n" :
(x % 10 == 3) ? "%drd armstrong number: %d\n" :
"%dth armstrong number: %d\n" ;
printf(format, j, i);
Here's my solution. Try to keep your problems divided rather than trying to solve them all in one function. I hope this helps.
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#define CUBE(n) (n*n*n)
char* getCountSuffix(uint16_t n) {
n %= 100; // We don't care about the hundreds place
if(n >= 10 && n <= 20) { // 10-19 always use "th" ("tenth", "eleventh", "twelveth", etc.)
return "th";
}
n %= 10;
switch(n) {
case 1:
return "st";
break;
case 2:
return "nd"; // edit: was "nt"
break;
case 3:
return "rd";
break;
default:
return "th";
}
}
bool isArmstrong(uint16_t n) {
uint16_t hundreds = n / 100;
uint16_t tens = (n % 100)/10;
uint16_t ones = n % 10;
return (CUBE(hundreds) + CUBE(tens) + CUBE(ones)) == n;
}
int main() {
size_t i, count;
for(i = 0, count = 1; i < 1000; i++) {
if(isArmstrong(i)) {
printf("%u%s. %u\r\n", count, getCountSuffix(count), i);
count++;
}
}
return 0;
}
You find a pattern and make use of that pattern. Find a program that converts Roman Numerals to numbers, see how they are extracting a pattern and achieving it.
PS: You are mixing up the presentation and implementation. Implementation should compute the armstrong number and should pass it to another method for display, which can keep track of it and display it whatever way required. Displaying is not the problem you want to solve here and I would propose dont spend too much time for this 1st, 2nd, 3rd cases.
Use printf's formatting capabilities. Replace all those else if printfs with:
printf("\n%dth", j);
The integer j will be substituted for %d. If you need to use (1st, 2nd, 3rd, 4rth) nd, th and st then have a few if statements to decide with one will be used, then printf using that one.
int sum = 0;
int count;
count = int.Parse(Console.ReadLine()); //Armstrong numbers from 0 to count
Console.WriteLine();
Console.Write(" Armstrong numbers from 0 to " + count + " are: ");
for (int c = 0; c <= count; c++)
{
sum = 0;
for (int i = 1; i <= c; i *= 10)
{
if (c / i % 10 >= 1)
{
int cube = (c / i % 10);
sum += cube * cube * cube;
}
}
if (sum == c)
{
Console.Write(sum + " ");
}
}

srand function is returning same values

Hey guys take a look at this program.
/* The craps game, KN king page 218 */
#include <stdio.h>
#include <time.h>
#include <stdbool.h>
#include <stdlib.h>
int roll_dice(void);
bool play_game(void);
int roll_dice(void)
{
int roll;
getchar();
srand((unsigned) time(NULL));
roll = rand() % 13;
if(roll == 0)
roll = roll + 1;
return roll;
}
bool play_game()
{
int sum = 0, wins = 0, loss = 0, point;
sum = roll_dice();
printf("You rolled: %d", sum);
if(sum == 7 || sum == 11)
{
printf("\nYou won!\n");
return true;
}
if(sum == 2 || sum == 3 || sum == 12)
{
printf("\nYou lost!!");
return false;
}
point = sum;
printf("\n\nYour point is: %d", point);
do
{
sum = roll_dice();
printf("\nYou rolled: %d", sum);
}while(sum != point);
if(sum == point)
{
printf("\nYou won!!!");
return true;
}
}
int main()
{
char c, wins = 0, losses = 0;
bool check;
do
{
check = play_game();
if(check == true)
wins++;
else if(check == false)
losses++;
printf("\nPlay Again? ");
scanf("%c", &c);
}while(c == 'Y' || c == 'y');
printf("\nWins: %d Losses: %d", wins, losses);
return 0;
}
The srand function keeps returning, same value 3 or 4 times, y is that?
I want different values each time when i roll the dice, copy the code and run it to see what i mean
srand() is a function that sets the seed for the rand() function. What you are doing here is setting the seed to the current time before every rand() you call, which, if called fast enough, will get you the same value (since it will reset to the same seed, which if fast enough will be the same time value).
What you'll want to do is call srand() once, when the program starts (at the start of your main() function)
Then call rand() every time you want a random number, like you are doing currently, but without calling srand() every time.

Resources