Why is my product cost average coming out at 0? - c

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders.
//Program written using multiple functions.
#include <stdio.h>
#define SIZE 5
void inputData();
void processingData(float costs[]);
float costs[5];
float sortedCosts[5];
int main()
{
inputData();
processingData(costs);
}
void inputData()
{
int i = 0;
printf("\nPlease enter five products costs.\n");
while (i < 5)
{
scanf("%d", &costs[i]);
i = i + 1;
}
}
void processingData(float costs[])
{
int i;
int j;
float sum = 0.00f;
float average = 0.00f;
for (i = 0; i < 4; ++i)
{
int j, min, temp;
min = i;
for (j = i + 1; j < 5; ++j)
if (costs[j] < costs[min])
min = j;
temp = costs[i];
costs[i] = costs[min];
costs[min] = temp;
}
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
sortedCosts[i] = costs[i];
for (i = 0; i < 5; ++i)
sum += costs[i];
average = sum / 5;
printf("Product Cost Average = %.2f\n", average);
}
Why is my product cost average coming out as zero? As far as I can see all of my variables are declared as float? I have tried all sorts of combinations and I cant seem to get it to work. I really appreciate your help!

scanf("%d", &costs[i]);
cost[i] is of type float in your program not int.
Use %f conversion specification to read a float.
Also:
temp = costs[i];
Your temp value is of type int but costs[i] is of type float. I don't think it is deliberate.

Use the "%f" modifier in scanf to get a float, rather than "%d".
Also, you
#define SIZE 5
but you use 5's throughout your code rather than SIZE. Use SIZE to reduce the possibility of bugs.
There's nothing wrong with
i = i + 1;
but that is much more commonly written as
i++;

Related

Creating a histogram in C

I have tried many different approaches and it keeps giving me errors...I am definitely not the best coder, please help! I have tried to create a histogram in many different ways, I know the logic behind making a histogram but I do not know how to implement that into C. I need to create a histogram for the x array.
The problem:
Write a computer routine to generate 2,000 values from the given cdf F(x)=x^4/16 on 0<=x<=2. Make a histogram of the 2,000 values and compare it to the theoretical cdf.
int main()
{
int i, b, d, e, j, bins=9, n=2000, y[2000], hist[9];
double seed = 12;
double temp=0, r[2000], temp2=0, x[2000];
int a = 1093, c = 18257, m = 86436;
printf("\nThis program will calculate random variates based on the given CDF\n :x^4/16 on 0<=x<=2\n ");
y[0]=seed;
for (i=1; i<n; i=i+1){
y[i] = (a*y[i-1] + c) % m;
temp = y[i];
r[i] = temp / m;
temp2 = r[i];
x[i] = pow(16*temp2,0.25);
printf("%d %.4lf %lf\n", y[i], r[i], x[i]);
}
//all of my attempts below
/*
int *buildHist(int bins, double min, double max, int n, double *data){
double *hist=malloc(bins*sizeof(int));
if (hist == NULL) return hist;
for (int i=0; i<n; ++i){
int bin=int( (data[i]-min)/((max-min)/(bins)) );
if ( (bin>=0) && (bin<n) ) hist[bin]++;
}
return hist;
}
int max = x[0];
for (d = 1; d < n; d=d+1){
if (x[d] > max)
max = x[d];
}
printf("The max is : %lf\n", max);
int min = x[0];
for (b =1; b<n; b=b+1){
if (x[b] < min)
min = x[b];
}
printf("The min is : %lf\n", min);
//Dividing data into bins
for (b = 0; b < n; b+1){
for (j = 1; j <= bins; j+1){
float bin_max = (float)j / (float)bins;
if (x[b] <= bin_max){
hist[j]+1;
break;
}
}
}
// Plotting histogram
printf("\n\nHistogram of Float data\n");
for (d = 1; d <= bins; d+1){
count = hist[d];
printf("0.%d |", d - 1);
for (e = 0; e < count; e+1)
{
printf("%c", (char)254u);
}
printf("\n");
}
*/
return 0;
}
I guess that your problem is that malloc() returns non-initialized memory. This means that your hist already contains garbage values which you then increment with hist[bin]++.
Use calloc() to allocate hist or use the memset() C library function to clear hist before use.

Calculate the mean of an array of n numbers in C

I'm new to C and I'm trying to master the basics so I've written a program which gives you the mean of tree numbers and it works, but when I try to write a more general version of it, as output I receive: Insert a series of numbers: "The mean of the numbers is -nan". Which means that I can not even insert the numbers. I don't now how to write the scanf part in a better way.
Here's the code:
#include <stdio.h>
int main() {
int p;
double n[p];
int i;
double sum = 0;
double m;
printf("Insert a series of numbers:\n");
for(int r = 0; r < p; r++) {
scanf("%lf", &n[r]);
}
for(i = 0; i < p; i++) {
sum += n[i];
}
m = sum / p;
printf("The mean of the numbers is %lf", m);
return 0;
}
int p;
You forgot to initialize p. Since p is an object of the automatic storage class, it has an indeterminate value.
Thus,
double n[p];
....
for(int r = 0; r < p; r++){
scanf("%lf", &n[r]);
}
for(i = 0; i < p; i++){
sum += n[i];
}
m = sum / p;
invokes undefined behavior.
Initialize p like f.e.
int p = 5;
Also don't forget to check the return value of scanf() if all items were assigned successfully, like for example:
if(scanf("%lf",&n[r]) != 1)
{
fprintf(stderr,"Error at scanning!");
return 1;
}

Array additions and averages

So this weeks homework is to: 'Write a program that inputs 6 integers and puts them into an Array. The program
then prints out the following: A list of all Array elements, from 0 to 5 and the sum and
mean value of all elements. NB The mean value of the array elements will not
necessarily be an integer. In order to convert an integer into a real (float) use
casting:
To turn the integer ‘x’ into a float use float(x)
E.g.:
Average = float(sum)/number of elements ;
(In this case the number of elements is 6)'
Not quite sure what I am doing wrong here but my code seems to give back incorrect answers and I can't figure out why.
Any suggestions would be greatly appreciated. I feel like I am going to fail this module as I have struggled with it since the introduction of functions, etc.
Anyway, here is my code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int numArr[5];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + i;
}
avg = sum /6;
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
'Write a program that inputs 6 integers
int numArr[5];
^^^^^
Change this loop
for (i = 0; i < 6; i++) {
sum = sum + i;
}
like
for (i = 0; i < 6; i++) {
sum = sum + numArr[I];
}
And change this statement
avg = sum /6;
the following way
avg = ( float )sum /6;
And you forgot to output all elements of the array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
and you may remove header <math.h> because neither declaration is used from this header in your program.
Your array isn't large enough to hold 6 numbers.
Change
int numArr[5];
to
int numArr[6];
Currently, you are accessing the array out-of-bunds, resulting in undefined behaviour.
There are couple other problems too:
1) You are not summing the array elements
2) You are doing integer division
Fix it, it'd look like:
#include<stdio.h>
#include<math.h>
int main(void) {
int numArr[6];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + numArr[i]; /* was summing `i` instead of numArr[i] */
}
avg = sum /6.0; /* was doing integer division */
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
sum = sum + i;
should be
sum = sum + numArr[i];
Array elements should be added.
Later
avg = sum/6.0
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
avg = (float)sum /6;
Notice numArr[i]
int numArr[5];
should be
int numArr[6];
and
for (i = 0; i < 6; i++) {
sum = sum + i;
}
should be
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
and
avg = sum /6;
should be
avg = sum/6.0 //because division of integer by an integer results by integer value. So we divide integer with a float (6.0) value

Fill a defined 2D Array with random numbers in C / Average / Max Value

I've created this 2D 21x21 array that has all it's values set to -1. I wrote it to print the address and value and somehow it only starts at [6][19] why?
What i want to do is to replace some of the -1 values with random numbers from 0 to 100 in the same array. I know i need to seed it with srand but i'm having problems connecting the functions since i'm a total beginner in C.
EDIT 1:
Now i can print the whole array and fill it with random numbers. For the -1 values i just assigned directly which for this case its fine.
What i'm trying now is finding the average of all the values and the maximum number, so what i have is:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[21][21], i , j;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("%3d" , a[i][j]);
}
printf("\n");
}
return 0;
}
// random seed
int GetRand(int min, int max);
int get() {
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
// average
int avg()
float sum=0.0;
for(i = 0; i <= 21; i = i + 1) {
for(j = 0; j <= 21; j = j + 1){
sum = sum + a[21][21];
}
printf("The the average number is %.2f\n", sum/21);
}
//find maximum of all values
int *pv = &a[0][0];
max = min = 0;
for (i = 1; i < i*j; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/j, max%j);
return 0;
}
For the average function the compiler tells me that expected a declaration before i, which is "float sum=0.0;" but i haven't been able to fix that yet.
For the finding the max function i'm not sure yet what i'm doing there, i just have a vague idea of how it's done...am i going in the right direction?
Thanks!
It's very simple: Just assign the result of your GetRand function to the matrix entry.

C program- find the lowest student score above, and the highest score below the boundary

I am finishing a program where I read in a bunch of non-negative doubles into an array, then calculate the mean and stand dev of the values. Then the mean plus the stand dev represents getting a B.
I am having trouble with the next part, where I need to find the lowest score from the array of numbers that will give me a B, and then the highest value in the array that did not get a B. I am having so much trouble with this part that any help would be amazing.
I also have to make the program stop when EOF is typed into it, but I can not figure that part out either, so any help with that would also be appreciated. For now I instead just made it work for all positive values and stop when a negative value is introduced, here is my code:
#include <stdio.h>
#include <math.h>
int main () {
int arr[100];
int y, x;
int i;
double mean = 0;
double std = 0;
double this = 0;
i = 0;
printf("Enter next number, EOF to stop > ") ;
scanf("%d",&x);
while (x >= 0) {
arr[i++] = x;
printf ("Enter next number, EOF to stop > " );
scanf("%d",&x);
}
y = i;
double sum = 0;
double sum1= 0;
for(i = 0; i < y; i++){
sum = sum + arr[i];
}
mean = sum / y;
for (i = 0; i < y; i++){
sum1 = sum1 + pow((arr[i] - mean), 2);
}
std = sum1 / ((float)y - 1);
this = mean + sqrt(std);
if (10 > y) {
printf("**You must enter atleast 10 scores***\n");
return 0;
}
printf("Mean = %.2lf, Standard Deviation = %.2lf\n", mean, sqrt(std));
printf("Scores above %.2lf get a B\n", this);
return 0;
}
Code:
#include <stdio.h>
#include <math.h>
int main () {
int arr[100];
int y, x;
int i;
double mean = 0;
double std = 0;
double margin = 0;
i = 0;
printf("Enter next number, EOF to stop > ") ;
scanf("%d",&x);
while (x >= 0) {
arr[i++] = x;
printf ("Enter next number, EOF to stop > " );
scanf("%d",&x);
}
y = i;
if (10 > y) {
printf("**You must enter atleast 10 scores***\n");
return 0;
}
double sum = 0;
double sum1= 0;
for(i = 0; i < y; i++){
sum = sum + arr[i];
}
mean = sum / y;
for (i = 0; i < y; i++){
sum1 = sum1 + pow((arr[i] - mean), 2);
}
std = sum1 / ((float)y - 1.0);
margin = mean + sqrt(std);
printf("Mean = %.2lf, Standard Deviation = %.2lf\n", mean, sqrt(std));
printf("Scores above %.2lf get a B\n", margin);
int below = arr[0]; // highest value in the array that will not get a B
int above = arr[0]; // lowest value in the array that will give a B
for (i=0; i<y; i++) {
if ((arr[i] > below) && (arr[i] < margin)) {
below = arr[i];
}
else if ((arr[i] > margin) && (arr[i] < above)) {
above = arr[i];
}
}
return 0;
}
First of all, if you intend to program in -ansi -pedantic C, all variables must be defined at the top of the block. e.g:
Correct:
func() {
variable v1;
variable v2;
perform_stuff();
}
In correct:
func() {
perform_stuff()
variable v1;
}
and now to your question:
if you wish to hold an array of double values, the array should be of type double and not of the type - int.
to find the lowest number in the array:
There are few possible options for that one, first, you could ask the user to enter the values from lowest to highest and then just reach to the array[0] (first location = lowest value). but if you do not/ can not, always use quicksort: http://www.cquestions.com/2008/01/c-program-for-quick-sort.html
to sort the array from lowest values to the highest and then find the value you wish using a binary search: http://www.cquestions.com/2008/01/c-program-for-binary-search.html
to search for the value you wish to.
or you could also make it work this way in the efficiency of O(N):
int heighest_smaller_than_mean = 0;
int smallest_smaller_than_mean = mean;
for(i = 0; i < mean; i++) {
if(heighest_smaller_than_mean < arr[i])
heighest_smaller_than_mean = arr[i];
if(smallest_smaller_than_mean < arr[i])
smallest_smaller_than_mean = arr[i];
}
Hope I understand you correctly :)
For the second question, do not read in the input using fscan(%d, &x), rather create a character array (for example, char [] str = new char[5];) and scan that with fscan(%s, &str). Then, compare the string to another string containing "EOF" using if (strcmp(str, eofStr) == 0) break. Use atoi to convert the string to an integer.
To find the lowest score with a B, store an integer that saves the lowest number with a B. Set the initial value to the A grade value. Iterate through the loop and compare to a score for each iteration. If the score is lower, but still a B, exchange the current lowest score with this score. Finish the loop and you will have the lowest score with a B. You can do the same thing to get the highest score without a B.
int low = this + sqrt(std);
for (int i = 0; arr[i] > 0; i++) {
if (low > arr[i] && arr[i] >= this) low = arr[i];
}

Resources