before I ask my question I would like to point out that I did look for the answers already, and I didn't find what I was looking for.
Please bear in mind that I am a beginner in terms of programming, so please don't assume that I know everything there is to know.
Right, to the question.
My question is : How do I add together numbers that are created by random number generator ? The difficulty that I have is the fact that the number of randomly generated numbers could be different every time the program is ran. To make it clearer, the amount of randomly generated numbers is dependent on the input from user, eg if the input is 9, the program will generate 9 random numbers. This makes it difficult for me to come up with the idea of how to add the random numbers together and display them.
Here is the source code from my program. I think it is important to mention that the random numbers change every time I run the program, which is how I want them to be ( I used srand() with time, and rand() ). Also, the problem that I have currently is that the program doubles the last randomly generated number instead of adding them all together.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
int turn_total;
time_t t;
int sum;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum = roll+roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Any help, ideas or clues would be greatly appreciated.
Yo need to initialize sum first also you are not adding properly.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
time_t t;
int sum = 0;
srand((unsigned) time(&t)); // the seed for the random number generator based on the current time
for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum += roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}
printf("The Total Turn Score is : %d", sum);
}
Use
srand( ( unsigned int )time( NULL ) );
and initialize variable sum. For example
long long int sum = 0;
//...
sum += roll;
//...
printf( "The Total Turn Score is : %lld", sum );
Your program is doubling the number that was generated because that's what you tell it to do in this line:
sum = roll+roll;
Instead, you need to add the current roll to the current value of sum:
sum = sum + roll;
And you need to initialize sum to 0 so that you start by adding just the first roll.
Think about it like rolling a dice multiple times and writing down what it was each time. You roll it once and get a 3, so you write down 3. You roll it again and get a 6, so you add 6 to the previous roll to get 9. You roll again and get 2, so you add 2 to 9 and get 11, and so on. The variable sum is where you write down the new number after every roll, but you're adding to what you wrote down before.
The way you had it before, you were completely disregarding the previous rolls. rolls in the loop only refers to the latest roll that you performed, and since the loop ends at some point, sum will be left as the sum of the last value of roll. This is why you were getting double the last number.
replace
sum = roll+roll
with
sum = roll+sum;
Related
I made a program and then it didn't worked. As in the other post someone advised me to trying to debug my programs, I learned it and debugged this one. Probably it has some basic errors of writting but that's because I've changed a lot of thing recently to understand what's happening. In third time when I input a value on screen on that loop, it changes my var "i" to that value instead of keeping that number in my array "grade".
First I tried to make it all in one loop, the first one, but as always it didn't help much, and then i wrote the code by this manner as you'll see
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j=0,sum=0,i=0;
int grade[]={0};
for(;j<100;j++){
printf("Type a grade:\t");
scanf("%d",&grade[j]);
if(grade[j]<10||grade[j]>20){
break;
}
}
for(;i<j;i++){
sum=sum+grade[i];
}
float average=sum/j;
printf("The average is: %.2f\n",average);
system("pause");
return 0;
}
The exercicise says that you need to read "x" grades from a student and it needs to be between 10 and 20, if the number is out of this range it stops the loop.After I just need to calculate the average os these grades.I don't really know if my var average is being calculated correctly, cause I didn't could reach over there because of my problem. If you input 11, 12 and 13 it should give to a sum of 36, but gaves me 26, i don't know how.
Erik, you should define your array in a coherent way. To allow the necessary number of elements, try defining a numeric constant. You could use it for both define the number of iterations of your cycle and the size of your grade array. You can also avoid a new cycle to calculate the sum of the array, you can do this operation while reading the grades, using only one for loop. Try this way:
#include <stdio.h>
#include <stdlib.h>
#define MAX_GRADES 100
int main()
{
int j,sum=0,i;
float average;
int grade[MAX_GRADES];
for(j = 0 ; j < MAX_GRADES; j++)
{
printf("Type a grade:\t");
scanf("%d",&i);
if ( (i<10) || (i>20) )
break;
grade[j] = i;
sum += i;
}
if (j > 0)
average = (float)sum/j;
else
average = 0;
printf("The average is: %d, %d, %.2f\n",sum, j, average);
system("pause");
return 0;
}
I want to make a random number generator where the user specifies the range and amount of generated numbers. I want it to make every number unique (no repeat). This is what I've done so far (it generates but some of them repeat, why?)
#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
int main()
{
srand(time(NULL));
int start, stop, amount;
system("chcp 1250 >nul");
printf("Welcome to random number generator!\n");
printf("\nWhat range? \nFrom: "); scanf("%i", &start);
printf("To: "); scanf("%i", &stop);
printf("\nHow many numbers?: "); scanf("%i", &amount);
int number[amount];
for(int i=0; i<amount; i++)
{
number[i] = rand() % ((stop+1)-start) + start;
for(int j=i; j>-1; j--)
{
if(number[i]==number[j])
{
number[i] = rand() % ((stop+1)-start) + start;
}
}
printf("\n%i generated number: %i", i+1, number[i]);
Sleep(10);
}
getch();
}
Your "check for dupes" loop is incorrect. You might find a duplicate, but then you don't check if that re-generated number exists in the stuff you ALREADY tested.
e.g. consider an array like this. user asked for 5 numbers, range 1-10
number[0] = 5
number[1] = 6
number[2] = 2
number[3] = 8
Now you're working on number[4]. You generate 2... You scan the array backwards and find that 2 is a dupe. So you generate a new number... and generate 8. But you don't reset your j loop - you just keep working backwards, and never see that 8 was already in the array.
What you should have is something more like:
for(int j=i; j>-1; j--) {
if(number[i]==number[j]) {
number[i] = rand() % ((stop+1)-start) + start;
j = i; // RESET THE LOOP
}
}
And note that your code can easily produce an infinite loop. e.g. consider someone asking for numbers in a range 1-3, and generate 4 of them. 1,2,3,?. The condition can never be satisfied, because you can't have 1-3 without at least one repeat.
So, even if we assume that rand() is a perfect random number generator, the numbers would repeat.
Lets say you have to generate 100 numbers. Say your start = 1 and stop = 100.
you generate a first number from 1 to 100, then the second and so on.. The more numbers you've used so far, the easier it is to get a duplicate.
Then you find a duplicate with that inner for-loop. You generate a new number for
number[i], but you have no guarantee that this number's unique. You may as well end up
setting number[i] to another duplicate.
If you want your code to work, you have to keep changing number[i] as long as it has a duplicate.
That's regarding the bug in your code.
On the other hand, this code is horribly inefficient, so you should consider optimising it if you plan on running this procedure often.
This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}
Create a program to find out the first perfect square greater than 1 that occurs in the Fibonacci sequence and display it to the console.
I have no output when I enter an input.
#include <stdio.h>
#include <math.h>
int PerfectSquare(int n);
int Fibonacci(int n);
main()
{
int i;
int number=0;
int fibNumber=0;
int psNumber=0;
printf("Enter fibonacci number:");
scanf("%i",&number);
fibNumber = Fibonacci(number);
psNumber = PerfectSquare(fibNumber);
if(psNumber != 0){
printf("%i\n",psNumber);
}
}
int PerfectSquare(int n)
{
float root = sqrt(n);
if (n == ((int) root)*((int) root))
return root;
else
return 0;
}
int Fibonacci(int n){
if (n==0) return 0;
if (n==1) return 1;
return( Fibonacci(n-1)+Fibonacci(n-2) );
}
Luke is right. If your input is n, then the Fibonacci(n) returns the (n+1)th Fibonacci number.
Your program check whether (number +1)th is perfect square or not actually.
If you enter 12, then there is output. Because the 13th Fibonacci number is 144. And it is perfect square. PS: print fibNumber instead of psNumber.
printf("%i\n", fibNumber);
Right now you're only calculating one Fibonacci number and then testing whether it's a perfect square. To do this correctly you'll have to use a loop.
First suggestion is to get rid of the recursion to create fib numbers. You can use 2 variables and continually track the last 2 fib numbers. They get added something like:
fib1=0;fib2=1;
for(i=3;i<MAXTOCHECK;i++)
{
if(fib1<fib2)
fib1+=fib2;
else
fib2+=fib1;
}
What is nice about this method is that first you can change you seeds to anything you want. This is nice to find fib like sequences. For example Lucas numbers are seeded with 2 and 1. Second, you can put your check for square inline and not completely recalculate the sequence each time.
NOTE: As previously mentioned, your index may be off. There is some arbitrariness of indexing fib numbers from how it is initially seeded. This can seen if you reseed with 1 and 1. You get the same sequence shifted by 1 index. So be sure that you use a consistent definition for indexing the sequence.
I'm new at programming, new on this site too, so hello...
I'm attempting to obtain a running total for integers one thru 10, but I'm getting gibberish answers and I just can't understand why.
To attempt to find out what was going wrong, I added the
printf(" running total is %d\n", sum);
line to the while loop, but just got more of the same nonsense...
please see http://codepad.org/UxEw6pFU for the results....
I'm sure this has a blindingly obvious solution...I'm just too dumb to see it though!
anyone know what I'm doing wrong?
#include <stdio.h>
int main(void) {
int count,sum,square;
int upto=10;
count = 0;
square = 0;
while (++count < upto) {
square = count * count;
printf("square of %d is %d",count,square);
sum =square + sum;
printf(" running total is %d\n", sum);
}
printf("overall total of squares of integers 1 thru 10 is %d\n", sum);
return 0;
}
You need to initialize sum to 0.
EDIT As others have stated after the fact, the reason you're seeing garbage is because sum isn't initialized and contains whatever is in memory. It can be anything, and your use of it with sum = square + sum is going to add square to the uninitialized value.
You are never initializing the value of sum.
The first time your code runs
sum = square + sum;
The value of sum (on the right side) is an arbitrary number because it has not been initialized. Therefore, the resulting value of sum (on the left side) is that arbitrary number plus square.
Simply add a sum = 0 statement like you have for count and square already.
Right off the bat, you do not initialize 'sum' to anything.
edit: A cleaned up version, though depending on compiler, you might need to enforce C99 mode, otherwise older compilers might not support initial declarations in the for loop.
#include <stdio.h>
int main()
{
const int COUNT_MAX = 10;
int sum = 0;
for ( int i = 1; i <= COUNT_MAX; ++i )
{
sum += i*i;
}
printf("The sum of squares from 1 to 10 is: %d\n", sum);
return 0;
}
Initialize sum with 0, otherwise it contains arbitrary data:
sum = 0;
See: http://codepad.org/e8pziVHm
sum is not initialized
You should do :
sum=0;
and remove
square=0;