Why is the program printing 0s? - c

I've gone over the code and re-written it several times already and each time I get 0s when printing the array and the mean. I'm using codeblocks as the ide.
Below is statlib.c
// Calculates the mean of the array
double calculateMean(int totnum, double data[ ])
{
double sum = 0.0;
double average = 0.0;
int i;
// adds elements in the array one by one
for(i = 0; i < totnum; i++ )
sum += data[i];
average = (sum/totnum);
return average;
}// end function calculateMean
Below is the other file
#include "statlib.c"
#include <stdio.h>
int main (void){
int i; // counter used in printing unsorted array
double mean = 0.0;
double data[10] = {30.0,90.0,100.0,84.0,72.0,40.0,34.0,91.0,80.0,62.0}; // test data given in assignment
int totnum = 10; // total numbers in array
//Print the unsorted array
printf("The unsorted array is: {");
for ( i = 0; i < totnum; i++){
printf(" %lf",data[i]);
printf(",");
}
printf("}\n");
//Get and display the mean of the array
mean = calculateMean(totnum,data);
printf("The mean is: %lf\n",mean);
return 0;
}

You are trying to print mean with a %lf format specifier. That format specifier isn't valid, so probably something goes wrong there.
The correct format specifier for double would be %f, and the l length modifier is only allowed for integer formatting. (For floating point there is L, making %Lf the correct format specifier for long double).

Related

how does adding a line of prtintf fix this?

I am new to the C language (I started to learn it a week ago). the program was having some random output so i wanted to see what was it storing in the variable. then the printf fixed it somehow.
#include <stdio.h>
int laske(float lista[]);
const int MAX = 3;
int main()
{
float lista[5], yhteispisteet;
int counter = 0;
do
{
printf("Anna %d. pisteet: \n", counter +1);
scanf("%f", &lista[counter++] );
printf("%d",lista[counter]); <-- if you remove this line it dosent work
}
while (counter < MAX);
yhteispisteet = laske(lista);
printf("\nYhteispisteet ovat: %.2f\n", yhteispisteet);
getchar();
return 0;
}
int laske(float lista[])
{
int rivi, tulos;
for (rivi=0; rivi< MAX; rivi++)
tulos = tulos + lista[rivi];
return tulos;
}
Three things to note from your code:
You are adding a float and an int when you do: tulos = tulos + lista[rivi];, without casting the input float to int like this: tulos = tulos + (int)lista[rivi]; Or better yet, just declare tulos as float, and return a float from your laske function, because the return value is again being assigned to a float yhteispisteet
You assign to lista[counter++] with the scanf, and then increment the counter (post-increment) and print the lista[counter](which is printing the incremented indexed value that did not take any assignments yet). It is better to increment counter++ after the printf function.
You did not initialize your variable tulos, and this gives you undefined behavior when your code is running, which is probably what you are seeing when you add and then remove the printf and then rerun

Need assistance in fixing an error in my code [duplicate]

This question already has answers here:
Can a const variable be used to declare the size of an array in C?
(5 answers)
Closed 10 months ago.
It is saying that the variable p in the final function int main needs to be a constant but I attempted to change it to a constant and it still didn't run. Any recommendations on ways to fix it?
#define _CRT_SECURE_NO_WARNINGS // Disable warnings (and errors) when using non-secure versions of printf, scanf, strcpy, etc.
#include <stdio.h> // Needed for working with printf and scanf
// defining a function to read input
void input(double* array, int p) {
// looping p times to read p values from user
for (int i = 0; i < p; i++) {
printf("Enter a value for #%d: ", i + 1);
scanf("%lf", &array[i]);
}
}
double processing(double* array, int p) {
// defining a variable to store sum of all values
double sum = 0;
// looping over p values in the array
for (int i = 0; i < p; i++) {
sum += array[i];
}
// return average = sum / size of array
return sum / p;
}
void output(double average) {
// displaying average of all the values
// displaying only one decimal point as given
printf("The average of the values is %.1lf\n", average);
}
int main(void) {
// Constant and Variable Declarations
// defining size and initializing it to 10 as mentioned
int p = 10;
// size of p
double array[p];
input(array, p);
double average = processing(array, p);
output(average);
return 0;
} // end main() '''
Maybe you could call your function so instead of making P a variable:
input(array, 10);
sorry if it doesnt work im new to c as well

How to extract digits after decimal point in float and store in char Array

I refered below question but I need to extract the digits after decimal and store in char *array
1.How to store float in array of float[]
2.Extract digits in float in python
Ex:
float = 1.24456
My length of char *array is 2
Expected Output:
array[0] = 2;
array[1] = 4;
array[2] = 4;
I need to implement this in C dynamically.
You can isolate the fractional part of a float by using the function modff in <math.h>, which returns the fractional part as the function's return value and the whole-number part as an argument by reference:
float f = 3.141592f;
float numpart, fracpart;
fracpart = modff(f, &numpart);
Once you're done that, you can create a string with a conventional string-building function:
char buf[100];
snprintf(buf, 100, "%f", fracpart);
Another option is converting the entire float to a string, and then using strchr(float_str, '.') to isolate the decimal part.
Slightly more mathematical approach, but arguably less flexible would be this:
#include <stdio.h>
#include <math.h>
int main()
{
float num = 1.24456;
int num_noDecimals = (int)num; //truncate decimals in original number
float num_onlyDecimals = num - (float)num_noDecimals; //obtain only the number after decimal
int x = 4; //number of digits past decimal to extract
num_onlyDecimals = num_onlyDecimals*pow(10,x); //move extracting digits left of decimal
int digits_forArray = (int)num_onlyDecimals; //truncate remaining digits right of decimal
char arr[x];
for(int i=x-1; i > -1; i--) { arr[i] = (char)(digits_forArray%10); digits_forArray = digits_forArray/10; }
for(int i=0;i<x;i++) { printf("arr[%d] = %d\n",i,arr[i]); }
}
Hopefully it's commented well enough to understand the steps being taken here.
In my code, I removed the integer part, then I reverse the float part to integer part by multiply each number of the float part by the number 10 then I classify each digit of in the array
My code :
int main()
{
float n = 1.2445601;
int m=(int)n;
float p=n-m;
int x=7,i=0,tab[x];
while(i<x)
{
p=p*10;
i++;
}
i=6;
while((int)p!=0)
{
tab[i--]=(int)p%10;
p=p/10;
}
for(int k=0;k<x;k++)
{
printf("\narray[%d] = %d ;",k,tab[k]);
}
printf("\n");
return 0;
}
If you just want the digits after the decimal point in variable, you could just have number - floor(number)
for example, if your number was 3.25, the calculation would be 3.25 - 3. This will give 0.25

Is this C function for finding the product of an array correct?

I am new to C and have a question about making a simple function in which I hand in a given array and also an integer that tells the number of numbers in that array. I wrote this code but I am unsure if it is correct. What I was trying to do was to make it so that I could find the product of all the numbers in the array.
#include <stdio.h>
#include <math.h>
double my_product (int n, double x[]);
int main (void)
{
my_product(n, x);
return 0;
}
double my_product (int n, double x[])
{
int i;
product=0;
for(i=0; i<n; i++)
{
product=x[i]*x[i+1]
}
return product;
}
I will comment your code, pointing out your mistakes:
double my_product (int n, double x[])
{
int i;
product=0;
/* The variable "product" needs to have a type.
In your case, since your values have type "double",
and a "double" return is expected,
of course you need to declare:
double product;
On the other hand,
it has not sense to initialize a product to 0,
since multiplication by 0 "kills" every value,
giving you a value 0, not matter what you do.
So, initialize in this way:
double product = 1.0;
*/
for(i=0; i<n; i++)
{
/* A semicolon is missing in the next line: */
product=x[i]*x[i+1]
/* In every step of the loop,
the variable "product" will hold the value
given by the multiplication of two consecutive values
in the array.
Thus, you lose every previous factor.
Also, when i == n you are in trouble,
because x[i] == x[n] is beyond the limits of the array,
which may cause access violation to memory.
You need a cumulative product.
Starting by the initialized value 1.0,
you have to multiply the previous value of "product"
with the present value of the array: x[i]
product = product * x[i];
Thus, in the step i, it can be proved that
the variable "product" contains the cumulative product
of the factors x[0], x[1], ... up to x[i].
A more compact notation in C can be provided by the *= operator:
product *= x[i];
*/
}
return product;
}
In the function main():
int main (void) {
my_product(n, x);
/* The function "my_product()" has been called with
undeclared parameters "n" and "x".
First, you have to declare and define the value of "n",
as much as the array "x", having type double:
double x[] = {3.0, 1.41, -2.3, 9.4, };
int n = sizeof(x)/sizeof(double);
The first line would declare an array "x" having type "double",
and initialized to hold 4 values, as it's seen there.
The second line would declare an "int" variable "n"
holding the number of elements in the array,
which can be computed as the size of x (measured in bytes)
divided by the size of the type "double"
(of course, in this example we have n == 4).
Finally, you need to do something with the result returned by
the function "my_product()".
If not, the returned value will be completely lost.
For example, to hold it in a variable, or to show it on screen.
double ans;
ans = my_product(n, x);
*/
return 0;
}
The code will look like this:
#include <stdio.h>
#include <math.h>
double my_product (int n, double x[]);
int main (void)
{
double x[] = {3.0, 1.41, -2.3, 9.4, };
int n = sizeof(x)/sizeof(double);
double ans;
ans = my_product(n, x);
printf("Product is: %f\n", ans);
return 0;
}
double my_product (int n, double x[])
{
product=1.0;
int i;
for(int i=0; i<n; i++)
{
product *= x[i];
}
return product;
}
In your function my_product you overwrite the value of product in the loop
for(i=0; i<n; i++)
{
product=x[i]*x[i+1]
}
So suppose your array x = {2, 3, 4}, then first product gets the value of 2*3, but then you overwrite it with the value of 3*4. What you probably want is to use a variable in which you accumulate the results of the multiplications (e.g. total = total * number).
Also, watch out with your indexing. In your current code i+1 can be larger than the number of elements in x, so you run out of the array.

C: Why are my functions returning 0 values?

I've got a short program that's supposed to pass an array of float values to three different functions to return the sum, average, and smallest value. I can't figure out why the functions are returning 0 values (or am I passing the array incorrectly?)
I'm sure I've missed something simple and fundamental, but have been staring at this too long and really can't see what's wrong.
Appreciate any input.
#include <stdio.h>
#define NUM 5
float array_sum (float arr[]);
float array_avg (float arr[]);
float array_min (float arr[]);
int main ()
{
float array_nums[NUM] = {1.23, 4.56, 7.89, 10.1, 2.34};
float arr_sum;
float arr_avg;
float arr_min;
arr_sum = array_sum(array_nums);
arr_avg = array_avg(array_nums);
arr_min = array_min(array_nums);
printf("\nThe sum of the elements in the array is %f.\n"), arr_sum;
printf("The average of the elements in the array is %f.\n"), arr_avg;
printf("The smallest value in the array is %f.\n\n"), arr_min;
return (0);
}
float array_sum (float arr[])
{
float sum = 0;
int i;
for (i = 0; i < NUM; i++)
{
sum += arr[i];
}
return (sum);
}
float array_avg (float arr[])
{
int i;
float avg;
float sum = 0;
for (i = 0; i < NUM; ++i)
{
sum += arr[i];
}
avg = sum/NUM;
return (avg);
}
float array_min (float arr[])
{
int i;
float min = arr[0];
for (i=0; i < NUM; ++i)
{
if (arr[i] < min)
{
min = arr[i];
}
}
return (min);
}
Your printfs have the arguments outside of the function:
printf("\nThe sum of the elements in the array is %f.\n"), arr_sum;
^ end of arguments
should be
printf("\nThe sum of the elements in the array is %f.\n", arr_sum);
As others pointed out, your printf statements are wrong; you placed the argument outside the brackets (inadvertently, you used the comma operator, which evaluates the thing on the left of the comma, then the right of the comma, and produces this last result).
If you use the -Wall compiler flag, your compiler will normally warn you (saying e.g. "missing format argument for %f"). In general, you should turn on most warnings when using C, as they often point out bugs and errors in your programs that can otherwise be hard to catch.
Your printf statements are incorrect. This is the right way to do it:
printf("\nThe sum of the elements in the array is %f.\n", arr_sum);
printf("The average of the elements in the array is %f.\n", arr_avg);
printf("The smallest value in the array is %f.\n\n", arr_min);
You can also limit the decimal places to be displayed by doing this:
printf("\nThe sum of the elements in the array is %0.2f.\n", arr_sum); //this will display 2 decimal places
At a quick glance, it' s a parenthesis issue:
printf("\nThe sum of the elements in the array is %f.\n"), arr_sum;
Should be:
printf("\nThe sum of the elements in the array is %f.\n", arr_sum);
Just a small mistake. corrected code is here,
printf("\nThe sum of the elements in the array is %f.\n", arr_sum);
printf("The average of the elements in the array is %f.\n",arr_avg) ;
printf("The smallest value in the array is %f.\n\n", arr_min);

Resources