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;
}
Related
My general goal with this question is to understand how to make use (say, print) of an array returned from an outer function. I'm using prime numbers as an example.
I'm new so going in-depth explaining... Sorry if there's un-needed info or misused terms :)
I defined a function "findprimes" to find every prime between 1 and x.
The function successfully prints an array of primes. However, I don't know if it returns the array of primes. And, if it does, I have no idea how to use said array in main().
This is the function 'findprimes':
int* findprimes(int x) {
int i, j, total=0;
int* numbers = (int*)malloc((x + 1) * sizeof(int));
/* initialization */
for (i = 0; i <= x + 1; i++) {
numbers[i] = 1;
}
/* find primes and assign prime=1 */
for (i = 2; i < sqrt(x); i++) {
if (numbers[i] == 1) {
for (j = i * i; j <= x; j = j + 2) {
if (j % i == 0) {
numbers[j] = 0;
}
}
}
}
/* count how many primes */
for (i = 1; i <= x; i++) {
if (numbers[i] == 1) {
total++;
}
}
/* put primes into their own array */
int* primes = (int*)malloc(total * sizeof(int));
for (i = 1,j=0; i <= x; i++) {
if (numbers[i] == 1) {
primes[j] = i;
j++;
}
}
//I want this part to be in main()
printf("The prime numbers between 1 and %d are: ", x);
for (i = 0; i < total; i++) {
printf("%d ", primes[i]);
}
return primes;
}
I want to print the 'primes' array in main, not in the function 'findprimes' itself. How can I do this?
int main() {
int n;
do {
printf("Enter a value for X>2: ");
scanf("%d", &n);
} while (n <= 2);
findprimes(n); //This returns 'primes' array
//I want to print 'primes' array here
}
Capture the return value in main():
int *primes = findprimes(n);
and use the array:
for (int i = 0; i < some_magic_number; i++)
{
printf("%d\n", primes[i]);
}
and remember to free the memory:
free(primes);
In fact, you also need to free numbers in the function.
The some_magic_number needs to be known — how does the main() function know how many elements are in the array? One way to fix that is to pass a pointer to the function that can hold the number of primes:
int *findprimes(int n, int *num_primes)
and use *num_primes = total; in the function before returning.
You could call the function with:
int some_magic_number;
int *primes = findprimes(n, &some_magic_number);
You'd probably choose an alternative name for the variable in main(), but it illustrates my point.
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.
I have been figuring out how to scramble numbers from array after user enters 10 different numbers by using rand(). It crushes when it arrives to adjust() function so feel free to point out my stupid mistake. Cheers. The top part is function, the bottom part is in main().
void adjust(int z[], int size)
{
int i, n, t;
for(i = 0; i < size; i++)
{
size = rand();
t = z[size];
z[size] = z[i];
z[i] = t;
}
printf("\nYour numbers have been scrambled and here they are: \n", t);
}
.....................
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = num; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
addNum(z, 10);
adjust(z, 10);
return 0;
The rand() function returns a number between 0 and RAND_MAX.
Hence, the array index can go well beyond its range.
To get a random index within a range from 0 to N -1 , use rand() % N.
Another issue is that in your for loop, in adjust function, you are destroying the original value of 'size'. That contains the length of your array and is used to check the terminating condition of your for loop. Hence, do not modify 'size'. Use another variable to store your random index.
for(i = 0; i < size; i++)
{
n = rand() % size; // n is between 0 and size-1
t = z[n];
z[n] = z[i];
z[i] = t;
}
// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
printf("%d ", z[i]);
}
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];
}
//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++;