Given the following code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define NPOINTS 200
#define NMEASURES 50
#define PI 3.1415f
double mcIntSingleExp1(int);
double mcIntSingleExp1(int n){
int i, countIn = 0;
double x,y, integral1, integral2;
srand(time(NULL));
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX)*PI;
y = (double)rand()/(double)RAND_MAX;
if(y <= sin(x))
countIn++;
}
integral1 = (PI * (double)countIn)/(double)n;
countIn = 0;
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX) + PI;
y = ((double)rand()/(double)RAND_MAX) -1;
if(y >= sin(x))
countIn++;
}
integral2 = (PI * (double)countIn)/(double)n;
return integral1 - integral2;
}
double mcIntSingleExp2(int);
double mcIntSingleExp2(int n){
int i;
double x, sum = 0;
srand(time(NULL));
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX) + 2*PI;
sum += sin(x);
}
return (1/(double)n) * sum;
}
void mcIntMultExp1(int, double [], int);
void mcIntMultExp1(int k, double res1[], int n){
int i;
for(i = 0; i < k; i++)
res1[i] = mcIntSingleExp1(n);
}
void mcIntMultExp2(int, double [], int);
void mcIntMultExp2(int k, double res2[], int n){
int i;
for(i = 0; i < k; i++)
res2[i] = mcIntSingleExp2(n);
}
double mean(double [], int);
double mean(double v[], int size){
int i;
double sum = 0;
for(i = 0; i < size; i++)
sum += v[i];
return sum/(double)size;
}
double stdDev(double [], int);
double stdDev(double v[], int size){
int i;
double avg, std_dev = 0;
avg = mean(v,NMEASURES);
for(i = 0; i < size; i++)
std_dev += (v[i]-avg)*(v[i]-avg);
return sqrt(std_dev/(double)size);
}
int main(){
double measure, deviation, res1[NMEASURES], res2[NMEASURES];
mcIntMultExp1(NMEASURES, res1, NPOINTS/2);
mcIntMultExp2(NMEASURES, res2, NPOINTS);
measure = mean(res1, NMEASURES);
deviation = stdDev(res1, NMEASURES);
printf("\nIntegral 1 = %.14lf\nStandard Deviation 1 = %.14lf\n",measure,deviation);
measure = mean(res2, NMEASURES);
deviation = stdDev(res2, NMEASURES);
printf("\nIntegral 2 = %.14lf\nStandard Deviation 2 = %.14lf\n",measure,deviation);
return 0;
}
In the stdDev function I noticed that each element of the vector v is equal to avg (v [0] = v [1] = ... = avg), so the standard deviation is zero! In fact, the elements of v should be those of res1 or res2. I do not understand what is wrong!
Your code probably runs quickly enough that time(NULL) will usually always return the same value. After doing an srand with a given seed, the following calls to rand will return the same values each time.
We usually only execute srand(time(NULL)) once at the beginning of a program.
Related
I am a beginner and am doing pretty bad in my class right now, I just can't get some of this stuff down. I am working on one of the final homeworks and can't figure out the problem with my code. It's probably really messy but the main thing I'm having trouble with right now is the getArea function. It won't run correctly when I call it and says 'expected expression before int'. Any help is greatly appreciated, thanks
//This program takes 18 numbers and puts it in a single dimensional array and a two dimensional array.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define COLMAX 3
#define ROWMAX 6
double triArea(double a, double b, double c);
double checkValidation(double a, double b, double c);
double func1(double values[][COLMAX], int);
int main(void)
{
unsigned int seed;
double tArea = 0.0;
int rand_int();
int loop;
int col;
int row;
int counter = 0;
srand(time(NULL));
int RandomArray[18];
int ArrayTwo[6][3];
printf("\nOne dimensional array\n");
for(loop = 0; loop < 18; loop++)
{
RandomArray[loop] = rand_int();
printf("%d ", RandomArray[loop]);
}
printf("\nTwo dimensional array\n");
for(row = 0; row < ROWMAX; row++)
{
for(col = 0; col < COLMAX; col++)
{
ArrayTwo[row][col] = RandomArray[counter];
counter++;
//int total = 0;
//total = total + array2[row][col];
printf("%d\t", ArrayTwo[row][col]);
getArea(ArrayTwo[row][col]);
//printf("The total is %d", total);
}
printf("\n");
}
printf("\n");
double total = 0.0;
double ArrayTwoTotal[ROWMAX][COLMAX];
total = func1(ArrayTwoTotal, ROWMAX);
printf("total is %.2lf \n", total);
system ("PAUSE");
return 0;
}
double checkValidation(double a, double b, double c)
//triangleValueA + triangleValueB >= triangleValueC) && (triangleValueB + triangleValueC >= triangleValueA) && (triangleValueA + triangleValueC >= triangleValueB
{
int count = 0;
//a = base, b = height, c = area
if ((a + b >= c) && (b + c >= a) && (a + c >= b))
{
}
}
//Calculate area of a triangle
double getArea(int[int][int])
{
double base, height, area;
area = base*height/2.0;
printf("The area is %.lf\n", area);
checkValidation(base, height, area);
return area;
}
//Function to get the totals of the 1 dimensional array
double func1(double ArrayTwoTotal[][COLMAX], int rows)
{
double sum = 0.0;
int i, j;
for(i = 0 ; i < rows ; i++)
{
for(j = 0 ; j < COLMAX ; j++)
{
sum += ArrayTwoTotal[i][j];
}
}
return sum;
}
//Function to find a random number
int rand_int()
{
int x = 0;
x = ((rand() % 100)+1);
return x;
}
There are a lot of things that you need to look at.
First getArea() function doesn't have any declaration. Please declare it first and in a correct way.
Calculating the sum of the first k numbers of the sequence a[0] = 1, a[k] = k*a[k-1] +1/k ( k = 1, 2, ... ).
UPD
There is still a problem with the recursive function ...What is the error?
#include <stdio.h>
#include <stdlib.h>
float m(float n){
float k=1;
float sum=k;
int i;
for (i=1; i<n;i++){
k = (i*k+1.0/i);
sum = sum+k;
}
return sum;
}
float Fn(float n)
{
if (n==0) {
return 1;}
return ((n*Fn(n-1)+1.0/n)+Fn(n-1));
}
int main(int argc, char *argv[]) {
float k;
printf("input k : ");
scanf("%f",&k);
printf("res %f \n",Fn(k));
return 0;
}
There were several issues in your code:
Integer division: 1/n = 0
There was a confusion between the term value Fn and the sum value
An iterative solution is simpler here than a recursive one
Here is a code, with both iterative and recursive implementations:
#include <stdio.h>
#include <stdlib.h>
float sum_fn(int n){
float Fk = 1;
float sum = Fk;
for (int i = 1; i <= n; i++){
Fk = i*Fk + 1.0/i;
sum += Fk;
}
return sum;
}
float sum_recursive(int n, float *sum){
if (n == 0) {
*sum += 1.0;
return 1.0;
}
float Fn = n * sum_recursive(n-1, sum) + 1.0/n;
*sum += Fn;
return Fn;
}
int main(int argc, char *argv[]) {
int k;
printf("input k : ");
scanf("%d", &k);
printf("k = %d\tsum = %f\n", k, sum_fn(k));
float sum = 0;
sum_recursive(k, &sum);
printf("k = %d\tsum = %f\n", k, sum);
return 0;
}
The rest of my functions work fabulously, however the last function has my goat. The goal of this function is to use pointers to obtain the values of two different arrays and add those values to a third array. However, when I run the main method to make the function run, it pauses for a second and provides a wedge exit code that does not work.
I've tried removing the if((sizeof(*ptr1)) == (sizeof(*ptr2)){
---insert code here---
}
from the for loop, however, the problem seems to be just the for loop itself.
//===================================Broken Code========================================
#include <stdio.h>
#define MAXIMUM 1000
int sumArrays(int arr1[], int arr2[]);
int addArrays(int arr1[], int arr2[]);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
for(int i = 0; i <= MAXIMUM; i++)
arrayOne[i] = i;
printf("Arrayone %d\n", arrayOne);
for(int j = 0; j <= MAXIMUM; j++)
arrayTwo[j] = j;
printf("ArrayTwo %d\n", arrayTwo);
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo));
printf("%d", addArrays(arrayOne, arrayTwo));
return 0;
}
int sumArrays(int arr1[],int arr2[]){
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum;
for(int i = 0; i < MAXIMUM; i++){
sum += *ptr_1 + i;
sum += *ptr_2 + i;
}
return sum;
}
int addArrays(int arr1[],int arr2[]){
int *ptr1 = &arr1[0];
int *ptr2 = &arr2[0];
int sum = 0;
int i = 0;
int arr3[0];
if(sizeof(*ptr1) == sizeof(*ptr2)){
for(int i = 0; i < MAXIMUM; i++){
sum += *ptr1 +i;
sum += *ptr2 +i;
arr3[i] = sum;
}
}
printf("The value of array3 is %d", arr3);
}
The other function works perfectly, but the addArrays function does a wedge exit and doesn't cooperate.
I expect the addArrays function to take the elements from each array, add them together and assign them to the third array.
Thank you for your time.
UPDATE: WORKING CODE
#include <stdio.h>
#define MAXIMUM 1000
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
int sumArrays(int arr1[], int arr2[], size_t len);
int addArrays(int arr1[], int arr2[], int arr3[], size_t len);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
int arrayThree[MAXIMUM];
for(int i = 0; i <= MAXIMUM; i++)
arrayOne[i] = i;
printf("Array One %d\n", ARRAY_SZ(arrayOne));
for(int j = 0; j <= MAXIMUM; j++)
arrayTwo[j] = j;
printf("Array Two %d\n", ARRAY_SZ(arrayTwo));
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo, ARRAY_SZ(arrayOne)));
printf("%d", addArrays(arrayOne, arrayTwo, arrayThree, MAXIMUM));
return 0;
}
int sumArrays(int arr1[],int arr2[], size_t len){
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum = 0 ;
for(int i = 0; i < len; i++){
sum += *ptr_1++;
sum += *ptr_2++;
}
return sum;
}
int addArrays(int arr1[],int arr2[], int result[], size_t len){
int *ptr1 = &arr1[0];
int *ptr2 = &arr2[0];
int *ptr3 = &result[0];
int sum = 0;
int sum2 = 0;
int i = 0;
for(int i = 0; i < MAXIMUM; i++){
sum = *ptr1 ++;
sum += *ptr2 ++;
result[i] = sum;
printf("The result of array 3 is %d\n", *ptr3++);
}
}
Here are some notes:
When you assign/pass/print the and array using the name of the array, you are actually passing the memory location of the first element in the array (a pointer).So when you write:
printf("Arrayone %d\n", arrayOne);
You will see the memory address of the first element of the array being printed. If you would like to print the entire array you will need to loop through it. In this case you would be printing 1000 integers which might be undesirable.
void printArray(int * array, size_t len)
{
while(len--)
{
printf("%d ", *array++);
}
}
To get the number of elements in an array you can do something like this:
sizeof(arrayOne) / sizeof(arrayOne[0])
and you can put it in a macro like this:
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
and call it like this:
ARRAY_SZ(arrayOne);
You cannot get the array size if you are receiving an array in a function (it has decayed to a pointer), instead you should pass the array size to the function too. Here because you initialize the arrays with the size MAXIMUM we don't actually need to calculate the array size, but we can just to show it works.
If you want to return an array (like in addArrays()) you should create an empty array and pass it to the function, then the function can update the array with the result.
When looping through an array you never want to do array[maximum] because the array indices range from 0 to maximum - 1
#include <stdio.h>
#define MAXIMUM 1000
#define ARRAY_SZ(x) (sizeof(x) / sizeof((x)[0]))
int sumArrays(int arr1[], int arr2[]);
int addArrays(int arr1[], int arr2[]);
int main()
{
int arrayOne[MAXIMUM];
int arrayTwo[MAXIMUM];
int arrayThree[MAXIMUM];
for(int i = 0; i < MAXIMUM; i++)
arrayOne[i] = i;
printf("Array one size %d\n", ARRAY_SZ(arrayOne));
for(int j = 0; j < MAXIMUM; j++)
arrayTwo[j] = j;
printf("Array Two size %d\n", ARRAY_SZ(arrayTwo));
printf(" The sum of the arrays is : %d\n",sumArrays(arrayOne, arrayTwo, ARRAY_SZ(arrayOne)));
addArrays(arrayOne, arrayTwo, arrayThree, MAXIMUM);
return 0;
}
int sumArrays(int arr1[],int arr2[], size_t len)
{
int *ptr_1;
int *ptr_2;
ptr_1 = &arr1[0];
ptr_2 = &arr2[0];
int sum;
for(int i = 0; i < len; i++){
sum += *ptr_1 + i;
sum += *ptr_2 + i;
}
return sum;
}
void addArrays(int arr1[], int arr2[], int result[], size_t len){
int *ptr1 = arr1;
int *ptr2 = arr2;
int sum = 0;
int i = 0;
for(int i = 0; i < len; i++){
sum = *ptr1 +i;
sum += *ptr2 +i;
result[i] = sum;
}
}
The following code is trying to find the averages of a set of numbers in C, but the median and the mean both do not return anything. How do I make it so the mean and the median both return a float? Am I returning an invalid value or?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
float mean(int arr[], int size){
int sum = 0;
for(int i = 0; i<size; i++){
sum += arr[i];
}
return ((float)sum/size);
}
int range(int arr[], int size){
int smallest = arr[0];
int largest = arr[0];
for(int i=0; i<size; i++){
if(smallest>arr[i]){
smallest = arr[i];
} if(largest<arr[i]){
largest = arr[i];
}
} int difference = largest - smallest;
return difference;
}
int mode(int arr[], int size){
int maxValue = 0;
int maxCount = 0;
for(int i = 0; i<size; i++){
int count = 0;
for(int j = 0; j<size; j++){
if(arr[j] == arr[i]){
count++;
}
} if(count > maxCount){
maxCount = count;
maxValue = arr[i];
}
} return maxValue;
}
float median(int arr[], int size){
qsort(arr, size, sizeof(int), compare);
float middleOfArray = size/2;
int roundedMiddleOfArray = rint(middleOfArray);
if(ceilf(middleOfArray) == middleOfArray){
return((float)arr[roundedMiddleOfArray]);
}
else{
return((float)arr[roundedMiddleOfArray] - arr[roundedMiddleOfArray-1]);
}
}
int main(){
int array[6] = {1,2,3,4,5,6};
int newMean = mean(array, 5);
int newRange = range(array, 5);
int newMode = mode(array,5);
int newMedian = median(array, 5);
printf("The mean is : %f \n", newMean);
printf("The range is : %d \n",newRange);
printf("The mode is : %d \n",newMode);
printf("The median is : %f \n", newMedian);
return 0;
}
Turns out the way you fix it is by declaring the mean and the median as floats not ints (in main).
i'm tryin' to print the time taken for a merge sort on an array of random numbers generated by the computer, whose size should be taken from the user during runtime, but it's givin' a segmentation fault. can anyone help correct my mistake?
part(int arr[],int min,int max)
{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}
main(){
int x, *b, i;
double t5;
printf("array size = \t");
scanf("%d", &x);
b = (int)malloc(x*sizeof(int));
srand(time(NULL));
for(i = 0; i<x; i++) b[i] = rand();
time_t t1 = 0;
time_t t2 = 0;
t1 = time(NULL);
part(b, 0, (x-1));
t2 = time(NULL);
printf("time taken for merge sort = %f sec\n", (t1 - t2));
}
There are several issues with the code here:
All relevant prototypes to system functions are missing, Fix this by including the necessary headers.
The prototype for merge() is missing, as needed by part(). Add it.
Functions not returning anything shall be typed as void. Declare them alike.
There is no need to cast the result of malloc(). And if it is done it should be done to the correct type: int * here not int!
time_t is an integer in most of the cases, so if it is don't use the conversion specifier for double when trying to print time_t, but the correct integer conversion specifier that is d for 32bit wide time_t or ld for 64bit wide time_t. However to print difference of time_ts use difftime(), which actually results in a double.
Last not least the temporary buffer in merge() doesn't scale. Make it max+1 elements wide.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void merge(int arr[], int min, int mid, int max);
void part(int arr[], int min, int max);
void part(int arr[], int min, int max)
{
int mid;
if (min < max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid + 1, max);
merge(arr, min, mid, max);
}
}
void merge(int arr[], int min, int mid, int max)
{
int tmp[max + 1];
int i, j, k, m;
j = min;
m = mid + 1;
for (i = min; j <= mid && m <= max; i++)
{
if (arr[j] <= arr[m])
{
tmp[i] = arr[j];
j++;
}
else
{
tmp[i] = arr[m];
m++;
}
}
if (j > mid)
{
for (k = m; k <= max; k++)
{
tmp[i] = arr[k];
i++;
}
}
else
{
for (k = j; k <= mid; k++)
{
tmp[i] = arr[k];
i++;
}
}
for (k = min; k <= max; k++)
arr[k] = tmp[k];
}
int main(void)
{
int x, *b, i;
printf("array size = \t");
scanf("%d", &x);
b = malloc(x * sizeof(int));
srand(time(NULL ));
for (i = 0; i < x; i++)
b[i] = rand();
time_t t1 = 0;
time_t t2 = 0;
t1 = time(NULL);
part(b, 0, x - 1);
t2 = time(NULL);
printf("time taken for merge sort = %f sec\n", difftime(t2, t1));
}
time uses a type called time_t. To use it to find an elapsed time in seconds you must do something like this:
time_t time1, time2;
double seconds;
time(&time1);
...
time(&time2);
seconds = difftime(time2, time1);
Also, remove the cast from malloc. malloc returns a void pointer which is implicitly cast to an int pointer for you:
b = malloc(x * sizeof(*b));