What can i do to make integer random everytime [duplicate] - c

This question already has answers here:
How to generate a random int in C?
(32 answers)
Closed 3 years ago.
I created a little guessing game, where you need to guess a number in 3 tries or you will fail. Now question is what can i do to make integer random every time i run program.
Here is a code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sN = 4;
int g;
int gC = 0;
int gL = 3;
int ofG = 0;
while(g != sN && ofG == 0)
{
if(gC < gL)
{
printf("Guess a number[1-10]: ");
scanf("%d", &g);
gC++;
}
else
{
ofG = 1;
}
}
if(ofG == 1)
{
printf("You Failed! [Out of guesses]\n");
printf("Secret number was (%d)\n", sN);
}
else
{
printf("Congratulations! You win!");
}
return 0;
}
Show me how i can do it and explain what you did and what command/function does if you can because i'm new and i don't understand things very well. I guess i need to use
srand();
but i never used it before so any help would be appreciated.

#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
/* random int between 0 and 9 */
int r = rand() % 10;

Related

My if statement is not working only the else statement prints in C [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 months ago.
I'm trying to build a word guesser where you guess a word from the given choice. The words are stored in an array. The player is losing even though they must win.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guess(int N) {
int number, guess, numberofguess = 0;
int myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}\n");
char str[20];
gets(str);
printf("your guess is %s\n", str);
if (str == myval[number]) {
printf("you win\n");
} else
printf("you lose\n");
printf("the number is %s", myval[number]);
}
main() {
int N = 9;
guess(N);
return 0;
}
I want to make the code in such a way when the player enters the code and it matches with the random output the if statement works.
Use strcmp while comparing the strings in C.
When creating an array from strings, you should create it as char*.
Using gets is not good practice
You should specify the return type of all functions, including main(), which should return an int.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void guess(int N) {
int number, guess, numberofguess = 0;
const char* myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}\n");
char str[20];
gets(str);
printf("your guess is %s\n", str);
if (strcmp(str,myval[number]) == 0) {
printf("you win\n");
} else
printf("you lose\n");
printf("the number is %s", myval[number]);
}
int main() {
int N = 9;
guess(N);
return 0;
}

How do I ignore certain scan calls when using scanf() in C? (READ BODY)

I apologize if the title is misleading in anyway, because I don't know where or how to start on this one.
Recently I wrote a math game that makes random numbers and turns them into equations. But all the program can do Is take in numbers, if I wanted to allow commands like say show-stats to show your stats. I have to write the command and then a number after for the command to get recognized like so
show-stats 0
score is 1
show-stats
0 //number is required for some reason
score is 1
This is a minimal example I wrote
#include <stdio.h>
#include <string.h>
int main() {
int bar;
char foo[]="";
int score = 1;
scanf("%s%i",foo,&bar);
if(strcmp(foo,"show-stats"))
{
printf("Score is %i",score);
}
if(bar == 2)
{
score = bar*2;
printf("Doubled Points.\n");
}
}
Here is the actual code, In case you need. Also, I'd like advisors on the actual code, like if its spaghetti or if something is performance consuming, or just what I can improve on in general if its not too much trouble. thanks in advance and I'm open to suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define VER 10
#define DIV "-----"
int main()
{
system("clear");
unsigned int x,y; //equation numbers
int ans,sum; //user answer
unsigned int max = 10; //max possible number that can be made, cannot go under 10.
int score; //what do you think?
char operation;
int correctAnswers = 0,wrongAnswers = 0;
printf("Math game\nVersion %i.\n",VER);
for (; ;)
{
//phase 1; make numbers.
srand(time(NULL));
x = rand() % max;
y = rand() % max;
//phase 2; make operation type.
operation = rand() % 2;
switch (operation)
{
case 0:operation = '+';sum = x + y;break;
case 1:operation = '-';sum = x - y;break;
}
//phase 3; write question to console and get user answer
printf("What is %i %c %i? ",x,operation,y); //get input
scanf("%i",&ans);
//phase 4; determine right answer
if (ans == sum)
{
score++;
correctAnswers++;
max++;
printf("Your correct! +1!\n");
printf("%sStats%s\nScore:%i\nMax possible number:%i\nCorrect Answers:%i\nWrong Answers:%i\n%s%s%s\n",DIV,DIV,score,max,correctAnswers,wrongAnswers,DIV,DIV,DIV); //print stats when user wins,is a seperate call for readability. same thing on line 53 but for loss
}
else
{
score--;
wrongAnswers++;
if(max>10){max--;}; //assures max doesn't go under 10
printf("Wrong! -1\n");
printf("%sStats%s\nThe correct answer was %i\nMax possible number : %i\nScore : %i\nCorrect Answers : %i\nWrong Answers : %i\n%s%s%s\n",DIV,DIV,sum,max,score,correctAnswers,wrongAnswers,DIV,DIV,DIV);
}
}
}
Thanks to DevSolar, I know how to do this. Using fgets() and strtol() you can collect the entire string, and parse it into the command and the number, I read up on strtol here https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
edit:
char str[30] = ""; //the string the user types
fgets(str,30,stdin);
char *ptr; //the part of the string turned into words
long ret; //the part of the string turned into numbers
ret = strtol(str, &ptr, 10); //parameter 1;source string that is parsed;//parameter 2; string part of source.//parameter 3; base
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);

How to return an array and print it in main()? [duplicate]

This question already has answers here:
Returning an array using C
(8 answers)
Closed 3 years ago.
Here is the question:
Write a function that takes a file handle f as a parameter and returns
the number of occurrences of all digits in the file found in the file.
Write a program to show how this function can be used to find the
number of digits in the file "abd.dat".
After I finished this question, I noticed it need a return in the function, I just do the print inside of the function. I made some try to modify the code to do the print in main() function, but it seems not work, the output becomes weird.
#include <stdio.h>
#include <stdlib.h>
#define BASE 10
int digits(FILE *);
int main()
{
FILE *fp = fopen("abc.dat", r);
digits(fp);
fclose(fp);
return EXIT_SUCCESS;
}
int digits(FILE *f)
{
long long num, digits;
int i, lastDigit;
int occu[BASE];
fscanf(f, "%lld", &num);
for (i = 0; i < BASE; i++)
{
occu[i] = 0;
}
digits = num;
while (digits != 0)
{
lastDigit = digits % 10;
digits /= 10;
occu[lastDigit]++;
}
printf(Occurrences of each digit in %lld is: \n, num);
for (i = 0; i < BASE; i++)
{
printf("Occurrences of %d = %d\n", i, occu[i]);
}
}
you can define your function to return int* instead of int
In this case you need to use malloc for not losing the array at the end of the function.
after this you can print it from the main

Factorial with while loop in C [duplicate]

This question already has answers here:
When should I use ampersand with scanf()
(3 answers)
Closed 3 years ago.
Hello friendly community,
i´m really new in coding and also here registred on stackoverflow, so excuse me when I ask such simple questions. I lack the understanding to understand why this code does not work, because even after compiling no error message appears.
My Code below shows my try to code a while loop, calculating the factioral and printing the total:
#include <stdio.h>
/* Factorial 5! = 5*4*3*2*1 */
main ()
{
int Wert;
int fak = 1;
scanf ("%d", Wert);
while ( Wert > fak) {
fak = fak * Wert;
Wert = Wert - 1;
printf ("%d", fak);
}
}
It should calculate the factorial after input of a number and print the total. Maybe this can´t work but i don´t understand the why.
Thank you for your time.
Firstly, scanf expects the address of Wert, not its value, and also update your while loop to compare with 1. Here's the fixed version:
#include <stdio.h>
int main(void)
{
int Wert;
int fak = 1;
scanf ("%d", &Wert);
while ( Wert > 1 ) {
fak = fak * Wert;
Wert = Wert - 1;
}
printf ("%d", fak);
}
Input:
5
Output:
120
But since factorials easily overflow integers, it may be a better idea to use double instead:
#include <stdio.h>
double fact(double d)
{
if (d < 1.0)
return 1.0;
return d * fact(d - 1.0);
}
int main(void)
{
double d = 0;
if (scanf("%lf", &d) != 1) {
perror("Failed to read stdin");
return -1;
}
printf("%lf! = %lf", d, fact(d));
return 0;
}
Input:
100
Output:
100.000000! = 93326215443944102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
Just keep in mind that floating point math is broken.

srand() in dice game [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}
You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.
Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

Resources