how to get my random function to work? - c

The random function is not working in the parameters set and I do not know why. Can anyone help? I need random numbers between 18 and 38 and I can't seem to get that and I do not know why.
Here's my code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
}typedef tires;
void getTireInformation(tires*, int);
void tirePressure(tires*, int);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", &(ptire + i) ->Manufacturer);
}
printf("all tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n",(ptire +i) ->Manufacturer);
}
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
srand(time(NULL));
ptire = rand()%(max - min)-min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}
Edit: Here's my updated function after making the suggested fixes
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
ptire = rand()%(max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}

It's not necessary to call srand(time(NULL)); every time it generates a random number. Put that in main(), before any function call.
Then change
rand() % (max - min) - min;
to
rand() % (max - min + 1) + min;
Say max = 3 and min = 1, you need rand() % 3 + 1 to generate a random number from 1 to 3 inclusively.
There is another problem, which have nothing to do with random number generating: The random numbers generated is assigned to ptire, that is, you are assigning a tires* with an int!
I've refined your code. Hope it will work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
} typedef tires;
// Prototypes
void getTireInformation(tires*, size_t);
void tirePressure(tires*, size_t);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
srand(time(NULL));
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, size_t size)
{
size_t i = 0;
for (i = 0; i < size; i++)
{
printf("Please enter the maker of the tire: \n");
scanf("%s", (ptire + i) -> Manufacturer); // just use str. &str actually causes undefined bahavior
}
printf("All tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n", (ptire +i) -> Manufacturer);
}
void tirePressure(tires* ptire, size_t size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
(ptire + i) ->tire_pressure[0] = rand() % (max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure[0]);
}
}
And here is the result when I run it:
Please enter the maker of the tire:
qwert
Please enter the maker of the tire:
fewqwe
Please enter the maker of the tire:
hcgexf
Please enter the maker of the tire:
zrbghcr
All tire make you entered ...just for verification:
qwert
fewqwe
hcgexf
zrbghcr
22
34
31
31
All numbers are between 18 to 38 now. Note that tire_pressure is an array containing two ints. Without knowing your purpose, I just gave random numbers to its first element.

Related

C : Trying to split an integer into an array returns array of length 2, no matter the size of the integer

So I want to split each digit of a decimal number into an array. I have the following code:
#include <stdio.h>
int * splitNumberIntoArr(int num) {
int i = num;
int modulus,newNum;
static int arr[5];
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
return arr;
};
int main() {
int num;
printf("Provide a number:\t");
scanf("%d", &num);
int *arr;
arr = splitNumberIntoArr(num);
int k;
for(k = 0; k <= sizeof(arr) / sizeof(arr[0]); k++) {
printf("%d\n",arr[k]);
return 0;
};
When num is an integer consising of 3 digits, the code works how it is supposed to.
However, when the input consists of more than 3 digits, the array that is returned by the splitNumberIntoArr()
function only returns an array of length 2.
for example,
Since I am new to C, I struggle to understand why this problem even exists, taking into consideration the fact that the declared array is of length 5: static int arr[5];
Your help would be greatly appreciated.
Try something like this:
#include <stdio.h>
#include <string.h> // for memset
void splitNumberIntoArr(int num, int *arr) {
int i = num;
int modulus, newNum;
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
}
int main() {
int num;
scanf("%d", &num);
int arr[32];
memset(arr, -1, sizeof(arr));
splitNumberIntoArr(num, arr);
for (int k = 0; k < sizeof(arr) / sizeof(arr[0]) && arr[k] != -1; k++) {
printf("%d\n",arr[k]);
}
}
In main(), the sizeof(arr) is known, because it lies on the stack.

how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}

Random numbers that do not match each other

I want to produce different numbers with C.
We can generate a random number using the stdlib library and the srand function.
For example; I want to produce a random number between 0 and 5.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[3];
srand(time(NULL));
for(i = 0; i < n; i++)
{
array[i] = rand() % 5;
printf("%d\n", array[i]);
}
return 0;
But the same numbers may coincide here.Like this:
2
4
4
1
How can I prevent this?
Maybe you can use something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[4];
// Fill an array with possible values
int values[5] = {0, 1, 2, 3, 4};
srand(time(NULL));
for(i = 0; i < n; i++)
{
int t1 = rand() % (5-i); // Generate next index while making the
// possible value one lesser for each
// loop
array[i] = values[t1]; // Assign value
printf("%d\n", array[i]);
values[t1] = values[4-i]; // Get rid of the used value by
// replacing it with an unused value
}
return 0;
}
Instead of random number you can generate random non-zero shift from the previous number:
#include <stdio.h>
#include <stdlib.h>
int myrand() {
static int prev = -1;
if (prev < 0)
prev = rand() % 5;
prev = (prev + 1 + rand() % 4) % 5;
return prev;
}
int main(void) {
int i;
for (i = 0; i < 20; i++)
printf("%d\n", myrand());
}

taking information from a structure and using in another function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to know if I can call the information that is in tire_pressure in the structure and use it in another function? Basically I am not sure how to call it from one to the other. Do I have to declare the function in tireTest? Which is the function I am trying to access the tire_pressure information at. Thanks for the help
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[0];
int pressure_change[0];
}typedef tires;
// Prototypes
void getTireInformation(tires*, int);
void tirePressure(tires*, int);
void tireTest(tires*, int);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
srand(time(NULL));
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
tireTest(ptire, 4);
return 0;
}// end main
//============================
void getTireInformation(tires* ptire, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", &(ptire + i) ->Manufacturer);
}
printf("all tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n",(ptire +i) ->Manufacturer);
}//end getTireInformation
//=======================================================================
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 35;
for (i = 0; i < size; i++)
{
(ptire + i) ->tire_pressure[0] = rand() % (max - min + 1) + min;
printf("The Tire pressure is: ");
printf("%d\n",(ptire + i) -> tire_pressure[0]);
}// end for
}// end tirePressure
//==============================================================
void tireTest(tires* ptire, int size)
{
int i = 0;
int min = 2;
int max = 5;
int change[0] = {0};
i++;
for (i = 0; i < size; i++)
{
change[0] = rand() % (max - min + 1) + min;
//(ptire + i) -> pressure_change[0] = rand() % (max - min + 1) + min;
printf("Pressure change from test %d: %d\n",i + 1, change[0]);
//(ptire + i) -> pressure_change[0] = change[0] + tirePressure;
//printf("%d\n", (ptire +i) -> pressure_change);
}// end for
}
I think you're making the problem more difficult than it is -- see if this simplification solves your problems:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define PRESSURE_MIN 18
#define PRESSURE_MAX 35
struct tires
{
char Manufacturer[40];
int tire_pressure;
int pressure_change;
} typedef tires;
// Prototypes
void getTireInformation(tires *, int);
void tirePressure(tires *, int);
void tireTest(tires *, int);
//===============================================================
void getTireInformation(tires *ptire, int size)
{
for (int i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", ptire[i].Manufacturer);
}
printf("all the tire makes you entered ... just for verification:\n");
for (int i = 0; i < size; i++)
{
printf("%s\n", ptire[i].Manufacturer);
}
} // end getTireInformation
//===============================================================
void tirePressure(tires *ptire, int size)
{
for (int i = 0; i < size; i++)
{
ptire[i].tire_pressure = rand() % (PRESSURE_MAX - PRESSURE_MIN + 1) + PRESSURE_MIN;
printf("The Tire pressure is: ");
printf("%d\n", ptire[i].tire_pressure);
} // end for
} // end tirePressure
//==============================================================
void tireTest(tires *ptire, int size)
{
int min = 2;
int max = 5;
for (int i = 0; i < size; i++)
{
int change = rand() % (max - min + 1) + min;
printf("Pressure change from test %d: %d\n", i + 1, change);
ptire[i].pressure_change = change + ptire[i].tire_pressure;
printf("%d\n", ptire[i].pressure_change);
} // end for
}
//===============================================================
int main()
{
tires tire[4];
srand(time(NULL));
getTireInformation(tire, 4);
tirePressure(tire, 4);
tireTest(tire, 4);
return 0;
} // end main

Counting number of searches

I updated my main and sequetialSearch and now it crashes when it runs. It compiles okay, but then crashes.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include "percentage.h"
#include "sequentialSearch.h"
#define searchAmount 100
int main(int argc, char *argv[])
{
int numbers[100];
int searches[searchAmount];
int testAmounts[searchAmount];
int i;
int where;
int searchSuccess;
int searchUnsuccess;
int percent;
int looker;
int sum;
int average;
srand(time(NULL));
for (i = 0; i < 100; i++){
numbers[i] = rand() % 200;
}
for (i = 0; i < searchAmount; i++){
searches[i] = rand() % 200;
}
searchUnsuccess = 0;
searchSuccess = 0;
sum = 0;
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searchSuccess++;
testAmounts[i] = looker;
}else{
searchUnsuccess++;
testAmounts[i] = looker;
}
}
for(i = 0; i < searchAmount; i++){
sum = sum + testAmounts[i];
}
average = sum / searchAmount;
percent = percentRate(searchSuccess, searchAmount);
printf("Total number of searches: %d\n", searchAmount);
printf("Total successful searches: %d\n", searchSuccess);
printf("Success Rate: %d%%\n", percent);
printf("Total number of tests ran: %d\n", average);
system("PAUSE");
return 0;
}
sequentialSearch.h
bool seqSearch (int list[], int last, int target, int* locn, int* looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
*looker++;
}
*locn = *looker;
return(target == list[*looker]);
}
Pass looker in by reference, so that you can access its value from the caller.
int looker;
...
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searches[i] += looker;
searchSuccess++;
}else{
searchUnsuccess++;
}
}
bool seqSearch (int list[], int last, int target, int* locn, int *looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
(*looker)++;
}
*locn = *looker;
return(target == list[*looker]);
}
By the way, you may wish to reconsider defining functions in your header file; this could cause problems with duplicate symbol when linking if you have more than one c file including this file.
Why not just pass looker in as an int*, use it essentially as you have been, look at the value after seqSearch(...) returns, and add it to a running total back in main()?
One problem is that the increment of looker in seqSearch is incrementing the pointer rather than the value. It should probably be:
(*looker)++;

Resources