My Code so far:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
int i;
int rollDice;
int firInp;
int secInp;
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): ");
scanf("%d", &firInp);
printf("Enter the amount of throws you want(MAX=499, MIN=1): ");
scanf("%d", &secInp);
srand ( time(NULL) );
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1;
printf("%d \n", rollDice);
}
}
else{
printf("Sorry, these numbers don't meet the parameters. Please enter a number in the right parameters.");
}
return 0;
}
I want to have percentages in my code. I think the way to do that is to first enter the output of my code into an array. If there's another way please feel free to let me know.
edit: I want the output to be something like this:
1 3 4 4 4 5
occurrence of 1: 16.6 percent
occurrence of 3: ..and so on
Instead of entering the output of the random function in an array you could just use that array as a counter, and incrementing the array at position rollDice every time a number appears. Than you could easily extract the percentage by summing all the elements of the array and by dividing each element by that sum.
You can create an array of integers, with size equals to the numbers of possible values your dice can output. Then you use it as a counter for the number of occurences you get, the index of the array will represent that output value (you can use rollDice-1 since 0 isn't a possible output of the dice), and the value at the index will be the number of occurences.
After you finish rolling the dice you just have to print the percentage like this:
for (int i=0;i<firInp;i++) { // firInp: n_faces = n_possible_values
printf("Occurrence of %d: %.1f percent\n", i+1, ((float)array[i]*100)/(float)secInp);
}
Related
Hello i'm trying to create a program where it counts the number of heads and tails in a coin flip simulator based on the number of coin flips the user inputs. The issue with this is that when i'm trying to count the number of heads and tails then increment them, it gives me just a random number and not within the range of flips given.
This is a sample output of my error
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886
Instead I want it to count it like this:
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3
Here's the program :
#include <stdio.h>
#include "getdouble.h"
#include <time.h>
#include <stdlib.h>
int main(void) {
printf("Coin Flip Simulator\n");
printf("How many times do you want to flip the coin? ");
int numFlip = getdouble();
if(numFlip == 0 || numFlip < 0) {
printf("Error: Please enter an integer greater than or equal to 1.\n");
}
int i = 0;
int numHead = rand();
int numTails = rand();
for (i = 0; i < numFlip; i++) {
if(numFlip%2 == 0) {
numHead++;
}
else {
numTails++;
}
}
printf("Number of heads: %d\n", numHead);
printf("Number of tails: %d\n", numTails);
return 0;
}
Thanks for the suggestions, it's my first time trying to use the random number generator.
I suggest you use an unsigned integer type for numFlip. The main issue is that you need to initialize numHead (sic) and numTails. You want to use srand() to seed the random number generate otherwise the result is deterministic. As you only have two options just record number of heads and determine the tails after the fact:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
printf("Coin Flip Simulator\n");
printf("How many times do you want to flip the coin? ");
unsigned numFlip;
if(scanf("%u", &numFlip) != 1) {
printf("numFlip failed\n");
return 1;
}
unsigned numHeads = 0;
for(unsigned i = 0; i < numFlip; i++)
numHeads += (rand() % 2); // removed ! when #Fe2O3 wasn't looking :-)
unsigned numTails = numFlip - numHeads;
printf("Number of heads: %u\n", numHeads);
printf("Number of tails: %u\n", numTails);
}
and example output:
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 2
Number of tails: 8
I have made a while loop and it works partly. I want the code to stop when the values entered are under the parameter, but it keeps going regardless of the output. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(rollDice > 0)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1;
printf("%d \n", rollDice);
}
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
I'm new to C btw.
edit: I want the loop to continue if the user input is more than 24, 499 respectively.
What you're doing is wrong. Variable rollDice is for storing the values of the outcomes rather than doing a condition check. It will have random values and since the values on the dice can't be negative or zero it may not exit the while loop. I don't know what will rand() will produce so I'm just assuming.
The range for rand() is [0,RAND_MAX), including zero and excluding RAND_MAX. But because of this expression (rand()%firInp) + 1 , you're adding one to it. So it will never become Zero.
You can use a flag variable and set it to 1. When the if conditions are met, you can set the flag to 0. It will exit the while loop.
Corrected code :-
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
int flag = 1;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(flag)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = ((rand() + 1)%firInp);
printf("%d \n", rollDice);
}
flag = 0;
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
EDIT :-
Also, division with 0 is undefined. rand() can attain value 0. You should add 1 to rand() rather than adding to whole modulus. It can create an error if the rand() will give 0 as an output.
I have started C recently and am having trouble make the computer think of a random number.
This is the code so far. I need help!
#include <stdio.h>
#include <stdlib.h>
int main ()
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", userin);
int r = rand() % 11;
if (r == userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Thx a lot guys it worked out!!!!
In your code, r will be a random number from 0 to 10. For a random number between 1 and 10, do this:
int r = rand() % 10 + 1;
Also, you should call
srand(time(NULL));
at the beginning of main to seed the random number generator. If you don't seed the generator, it always generates the same sequence.
There is issue in your scanf statement as well.
You should use
scanf("%d", &userin);
instead of
scanf("%d", userin); /* wrong - you need to use &userin */
scanf needs the address of variables at which it will store the value. For a variable, this is given by the prefexing the variable with &, as in &userin.
There are few issues in your code.
not reading into the address & of your variable using scanf
not considering "legitimate" values of input, result of rand()%11 can also be 0
not checking against "illegal" input values, which can "alias" the result.
not properly initializing seed of the pseudo-random rand() function, so it always returns the same result.
Using printf for debugging your code, as in the following example, based on your code can help a lot:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DEBG 1
int main (void)
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
if(scanf("%d", &userin) != 1){ // read into the variable's address
printf("Conversion failure or EOF\n");
return 1;
}
if(userin < 1 || userin > 10){ // check against "illegal" input
printf("Offscale, try again\n");
return 1;
}
srand(time(NULL)); // initialize the seed value
int r = 1 + rand() % 10; // revise the formula
if (DEBG) printf("%d\t%d\t", r, userin); //debug print
if (r==userin){
printf ("you are right\n");
}else{
printf("Try again\n");
}
return 0;
}
Please, also consult this SO post.
Problems :
scanf("%d", userin); //you are sending variable
This is not right as you need to send address of the variable as argument to the scanf() not the variable
so instead change it to :
scanf("%d", &userin); //ypu need to send the address instead
and rand()%11 would produce any number from 0 to 10 but not from 1 to 10
as other answer suggests, use :
(rand()%10)+1 //to produce number from 1 to 10
Solution :
And also include time.h function to use srand(time(NULL));
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", &userin);
int r = (rand() % 10)+1;
if (r==userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Why use srand(time(NULL)) ?
rand() isn't random at all, it's just a function which produces a sequence of numbers which are superficially random and repeat themselves over a period.
The only thing you can change is the seed, which changes your start position in the sequence.
and, srand(time(NULL)) is used for this very reason
This should work
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int userIn = 0; //I like to initialize
printf("Guess a number from 1 to 10\n");
scanf("%d", &userIn);
srand(time(NULL)); //seed your randum number with # of seconds since the Linux Epoch
int r = (rand()%10)+1; //rand%11 gives values 0-10 not 1-10. rand%10 gives 0-9, +1 makes sure it's 1-10
if (r == userIn)
{
printf ("you are right\n");
}
else
{
printf("Try again\n");
}
return 0;
}
Edit: You may want to implement code to verify that the user input is in fact an integer.
I know this is going to be something of a silly slip or oversight on my behalf, but I can't get the array in this to print out correctly. When I run the code and put in my inputs, I get seemingly random numbers.
For example,
number of rooms was 1
wattage of lights was 2
hours used was 2
TV/computers was 2
The output I got was 3930804. What did I miss?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
int room[20] = {0.0};
int i;
int rooms = 0;
char option = 0;
int lights[20];
int hrsUsed[20];
int Telly_Computer[20];
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input wattage of lights");
scanf_s("%d", (lights+i));
printf("input number of hours use/day (average)");
scanf_s("%d", (hrsUsed+i));
printf("input number of TV/Computers");
scanf_s("%d", (Telly_Computer+i));
}
printf("%d \n", lights);
}
printf("%d \n", lights);
You're printing the array directly. You need to loop over it and print the elements one at a time.
int i;
for (i = 0; i < 20; ++i)
printf("%d\n", lights[i]);
You are just printing the address of lights (and using UndefinedBehavior by the way, address must be printed with %p). You must use a loop to print out all of the contents of each array slot.
for(int i=0;i<(sizeof(lights)/sizeof(int));i++)
printf("%d\n",lights[i]);
I'm having some issues on my code to get the highest number on an array of 5 elements, this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[4];
int x;
int main() {
for(x=1;x<6;x++) {
printf("Give me the time of runner 1: ");
scanf("%f",timerunner1[x]);
}
return 0;
}
This works perfectly, the output is:
Give me the time of runner 1: 14
Give me the time of runner 1: 3
Give me the time of runner 1: 10
Give me the time of runner 1: 5
Give me the time of runner 1: 2
How can I get the highest and lowest number of the array?
Maybe using a for or if.. How?
Thanks!
It doesn't work actually, you need to use the address of operator '&' to store the value in the array.
scanf("%f", &timerunner1[x]);
Also, your array isn't large enough to store the 6 integers that your loop is requiring and subscripting of an array starts at zero and ends at 5 (for 6 elements).
You can then either have another loop AFTER reading all your values to calculate the maximum or calculate it on the fly as below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[6];
int x;
float maximum = 0.0f;
int main() {
for (x = 0; x < 6; x++) {
printf("Give me the time of runner 1: ");
scanf("%f", &timerunner1[x]);
maximum = maximum > timerunner1[x] ? maximum : timerunner1[x];
}
printf("%f\n", maximum);
return 0;
}
Also, this code only works on positive values because maximum is initialised to zero and will always be larger than any negative value, if you need negative values, you should be able to experiement and figure that out.
Ok, in this program you will have to load the time of each player manually.
/* StackFlow
Find the highest of an array of 5 numbers */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
float timerunner1[ 5 ] ={ 0 };
float highest;
int highestindex, i;
/* Data input*/
for( i = 0; i < 5; i++ ){
printf( "\nEnter the %d element of the array: ", i );
scanf( %f, timerunner1[ i ] );
}
/* Considering that the first generated number is the highest*/
highest = timerunner1[ 0 ];
highestindex = 0;
/* The first element of an array is [0] not [1]*/
for( i = 1; i < 5; i++ ) {
/* if the next element in the array is higher than the previous*/
if ( highest < timerunner1[ i ]){
highest = timerunner1[ i ];
highestindex = i;
}
}
printf("\nThe highest time of the runner %d is: %f \n", highestindex, highest);
return 1;
}