I am trying to create a Dice Roll game where the user can roll up to 6 dice at a time. I am attempting to accomplish this by integrating pointers into my code. I am getting an output, with the desired amount of rolls as given by the user, but the output is incorrect. It is printing a pattern instead of printing random numbers. Any help is appreciated.
How many dice would you like to roll?
user input: 4
output: 3 0 3 0
How many dice would you like to roll?
user input: 5
output: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>
void tossDie(int []);
int main() {
int diceArray[6] = { 0 };
int num = 0;
int x;
do {
printf("\nHow many dice would you like to roll? Please enter here: ");
scanf_s("%d", &num);//user enters amount of dice they want to roll)
if (num < 1 || num > 6) {
printf("\n\nPlease enter a number between 1 and 6.\n\n");
}
} while (num < 1 || num > 6);
tossDie(diceArray);
//print dice roll numbers
for (x = 0; x < num; x++) {
printf("%d ", diceArray[x]);
}
return 0;
}
void tossDie(int numbers[]){
int randomNum;
int x;
srand(time(NULL));
randomNum = (rand() % 6) + 1; //random # between 1 - 6
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
Move srand(time(NULL)); to main(). Only needed once.
Only call x++ only per loop, not twice, to assigned all 6 elements of the array.
Move randomNum = (rand() % 6) + 1; to inside for loop to get different values.
Check return value of scanf_s("%d", &num); against 1, before using num.
Tip: Use an auto-formatter to save time and improve code presentation.
Design: I'd expect tossDie(int numbers[]) to also receive a num to indicate numbers[] width.
Before I answer, please note that I don't program in C, so there may be some language-specific things that I am missing.
In your tossDie() function, you set the value of randomNum once, but don't reassign it after that. Therefore, your output should return the same number for all values in the array, like such:
Input: 5
Output: 3 3 3 3 3
To fix that, you should put the variable declaration in the for loop (if you want to use a variable at all).
Additionally, you initialise the random variable every time you run the method. Instead, you should declare it once, in the main method.
Also, there's a little issue in this block of code:
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
You increase x twice in here: both in the first line and the third line. Instead, you should delete the x++ in the third line and have just the x++ in the first line.
Let me know if you have further questions or if there are still problems.
Related
**This was a deleted question but I remade it so it easier for this community to understand what I'm asking
Here is my code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int row;
int col;
int x;
int y;
int i = 9;
int count[i];
printf("Enter the size of your array: ");
scanf("%d %d", &row, &col);
int arr[row][col];
//This will read the rows
for (int x = 0; x < row; ++x) {
for (int y = 0; y < col; ++y) {
printf("Enter row %d: ", x);
scanf("%d", &arr[x][y]);
}
}
//This will create a count for the rows
for (x = 0; x < row; ++x) {
for (y = 0; y < col; ++y) {
++count[arr[x][y]];
}
}
//This will count if digits repeat in the rows and print it
printf("\nTotal count for each digit:\n");
for (int j = 0; j < 10; ++j) {
printf("Digit %d occurs %d time%s\n", j, count[j], count[j] > 1 ? "s" : "");
}
return 0;
}
Notes on the code
I made i = 9 because the max number the user should enter is 9
On the "This will read the rows" there should be two printf's
"Enter Row 0"
"Enter Row 1"
How would I go and make it so the user would enter a set of numbers for the user to enter in both the rows. When I compile it just keeps saying "enter row 0: enter row 0: enter row 0". The program should find out how many times a number between 0 and 9 was entered. The final result should look like this
Enter the size of your array: 2 6
Enter row 0: 0 1 2 3 4 5
Enter row 1: 0 1 6 7 8 9
Total count for each digit:
Digit 0 occurs 2 times
Digit 1 occurs 2 times
Digit 2 occurs 1 time
Digit 3 occurs 1 time
ect. This would keep going until it the program hits "Digit 9 occurs however many times.
When I compile without the printf it runs through 3 rows when it should be 2 and most of the numbers that the compiler gives out are wack except for 2 digits
Ex The Digit 1 occurs 3 times
Digit 2 occurs -343589435 times
Thanks for any help!
There are ten digits 0-9. So the array count should have ten elements. Also the array need to be initialized.
Either use an array with the size specified by a constant expression and initialize it in a declaration like
#define N 10
//...
int count[N] = { 0 };
Or use a variable length array and initialize it using the function memset declared in the header <string.h>
For example
#include <string.h>
//...
int i = 10;
int count[i];
memset( count, 0, i * sizeof( int ) );
Otherwise if the array is not initialized it will have indeterminate values.
This program tests Goldbach's Conjecture, printing a given even integer as the sum of two primes. After printing the first one, the given integer is to iterate by 2 , then find the sum of two primes for that integer. And so on until the program is interrupted by the user.
This problem is that the program prints a '0' after every executed print statement.
The code:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
The output:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
What I want it to look like:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
use just GC(goldsum);
instead of printf("%d\n", GC(goldsum));
Maybe you misunderstood the return 0; we put in main(). Every function has to return the value we desire. In the case of main we want 0 because that means everything was OK. In the case of your function the return value should be what YOU want from it.
Edit: re-read the question and adding this: Since you don't want a return value from you function you should declare it as void and not have it in a printf() because all the printing you want is in your function.
Void functions do not return a value, so that is what you want.
I am trying to do my homework, which is some sort of game.
This is a part of it and I'm trying to create a function which puts 18 (9 in one team and the other 9 in another) different players on the field. player is a struct which has a name and coordinates. So I tried to write this function and had several problems. I think I have mostly fixed them, but I don't understand what's wrong with it now. Basically this function gives all the players random x and y coordinates, but as I have to make sure that they don't match, I created 2 lists x's and y's. The program takes all the players and add's their x coordinates to x's list if the current player x coordinate matches any x coordinates in x's list, then the program checks the same player's y coordinate and checks if it matches the coordinate of y of the same object in y's list. So if both x and y math, then the program runs again by recursion. The problem I get is that the coordinates I get every time I run the program are same. they don't match but they are not really random cause they don't change when I run them again.
I think I have tried all my knowledge and skills but still can't understand the problem of my code.
Can you please tell me what's wrong with this code?
void random_positions()
{
int i,j;
int xs[17],ys[17];
for(i= 0; i<9 ; i++)
{
players[i][0].x = rand() % 25;
players[i][0].y = rand() % 25;
players[i][1].x = rand() % 25;
players[i][1].y = rand() % 25;
printf("A%d x = %d y = %d \n",i+1,players[i][0].x,players[i][0].y);
printf("B%d x = %d y = %d \n",i+1,players[i][1].x,players[i][1].y);
}
for(i = 0; i < 9 ; i++)
{
xs[i] = players[i][0].x;
xs[i+8] = players[i][1].x;
ys[i] = players[i][0].y;
ys[i+8] = players[i][1].y;
for(j = 0; j <= i ; j++)
{
//printf("j%d start\n",j);
if(i != j && xs[i] == xs[j])
{
//printf("i%d start\n",j);
if(ys[i] == ys[j])
{
return random_positions();
}
//("j%d done\n",j);
}
//printf("j%d done\n",j);
}
}
}
A computer is (usually) a deterministic machine; if you run the same program twice, you will get the same answer.
A random number generator generally takes a seed, an initial value that it uses to initialize itself before it starts producing random numbers; give it a different seed, and you will get a different sequence. One way to do this is to give it the current time as a seed:
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
/* initialize random seed: */
srand (time(NULL));
/* generate random number between 1 and 10: */
int num = rand() % 10 + 1;
printf("%d\n", num);
return 0;
}
This question already has answers here:
Why for loop in C only passes once?
(2 answers)
Closed 3 years ago.
int input;
int factorial;
int half;
printf("Enter the number you wish to calculate: ");
scanf("%d", &input);
for(x=1; x<input; x++);
{
half = input - 1;
factorial = input * half;
}
printf("%d\n", factorial);
return 0;
It's running once, giving me the input number * (input number - 1), exam, input is 5 its giving out 20. What am I doing wrong that is preventing it from continuing running?
You have a ; after the for-loop. Remove that and you'll be fine:
for(x=1; x<input; x++) {
// your stuff
}
You still have to fix another error in your loop, as mentioned in the other answers.
You don't change input in your loop, so your code boils down to (for your sample input of 5):
for (i = 1; i < 5; i++) {
half = 5 - 1;
factorial = 5 * 4;
}
factorial 5 (5!) would be 5 * 4 * 3 * 2 * 1, which should be:
factorial = 1;
for (i = input; i > 1; i--) {
factorial = factorial * i;
}
What am I doing wrong?
There are many things that you are doing wrong:
Naming a variable half is wrong, unless you assign a value that is truly a half of something to it
Your loop does not use the previous value of factorial
You always multiply input by input-1, and never change the input
You do not initialize factorial to 1
P.S. The fact that your loop runs empty is the least of your troubles.
P.P.S. To do it right, consider how you do it on paper: you start with 1, and then keep multiplying the previous result by numbers from 2 to input. Now write the same algorithm as a C program: use factorial as your intermediate result, and x from the loop as your "current number between 1 and input.
You're not actually changing the state, so you should only ever get input * (input - 1). Why? Well, half will always be input - 1, and input will never change. Meanwhile the value of factorial is simply assigned to that product every time you step through the loop.
I think what you intended is
factorial = 1;
// no sense in starting from 1, factorial already is 1
for(x = 2;
// using <= so as to *include* the original input value.
x <= input; x++)
{
// the same things a factorial = factorial * x
factorial *= x;
}
BTW: You may wish to compensate for negatives too.
Your loop uses the same values each time (input and half)
try
factorial = 1;
for(x=2; x<=input; x++)
{
factorial *= x;
}
I am writing a program in C that will roll two dice and output the sum.
The game is easy enough and now I am incorporating a function and Looping so that a using will make several attempts. The problem is that the score never changes after the first attempt. So I know the function is working but somehow the loop is throwing things off. Here is my code:
#include<stdio.h>
//Function prototype
int RollScore(int , int);
main()
{
int LoopCount;
LoopCount = 0;
for(LoopCount = 0; LoopCount < 11; LoopCount ++)
{
//Declare Variables
int DieOne,DieTwo,DiceScore;
// One and Two will be hidden only Score will be output
DieOne = 0;
DieTwo = 0;
DiceScore = 0;
printf("\n\n\tTo win you need a score of 7 or 11.");
printf("\n\n\tPress a key to Roll the Dice!");
//Trigger Random number generator and remove previous text
getch();
system("cls");
DiceScore = RollScore(DieOne , DieTwo);
//Create Condition to either show user a win/lose output
if (DiceScore == 7 || DiceScore == 11)
{
printf("\n\n\n\t\tYou Rolled a score of %d" , DiceScore);
printf("\n\n\n\t\tCongratulation! You win!");
LoopCount = 11;
}//end if
else
{
printf("\n\n\n\t\tYou Rolled a score of %d" , DiceScore);
printf("\n\n\n\t\tSorry you have lost! Thanks for playing!");
printf("\n\n\t %d Attempt!" , LoopCount);
}//end else
//Prevent the IDE from closing program upon termination
getch();
system("cls");
}//End For
}
//Function definition
int RollScore (int Dieone , int Dietwo)
{
return (srand() % 5) + 1 , (srand() % 5) + 1;
}
return (srand() % 5) + 1 , (srand() % 5) + 1;
Call srand once to seed the random number generator and then call rand to get a random number.
Basic rand function documentation with an example.
srand() is used to initialize seed of a random numbers generator , rand() is the function that actually returns random number so you need to call srand() once before the for loop,
First of all, to get a value between 1 and 6 you have to do something like srand() % 6 + 1. Modulo 5 yields a value between 0 and 4, adding 1 you'll get a number between 1 and 5, 6 will never come out.
Second you want to return the sum of two num, you only return the value of the second draw. Try :
//Function definition
int RollScore (int Dieone , int Dietwo)
{
return (srand() % 6) + 1 + (srand() % 6) + 1;
}
Don't forget to use pointers if you want the results of the draws ...
//Function definition
int RollScore (int *Dieone , int *Dietwo)
{
*Dieone = srand() % 6 + 1;
*Dietwo = srand() % 6 + 1;
return *Dieone + *Dietwo;
}