I have to create a function called print_array that takes two parameters: a float array and an integer (denoting the length of the array). The function should print the entire array of floats to a precision of two decimals. E.g.,
float a[] = {1.555, 3, 1.645, 178};
print_array(a, 4);
It should give:
1.55, 3.00, 1.64, 178.00
My code goes as follows (a bit messy):
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int times_two(int a);
void print_int(int a);
int half(int a);
void print_float(float a);
void max(float a);
float average(float a);
void print_array(float a, int b);
int main (void)
{
int z = get_int("First Value for exercise 3? ");
int g = get_int("Second Value for exercise 3? ");
int max_value_1 = get_int("First Value (max) for exercise 4? ");
int max_value_2 = get_int("Second Value (max for exercise 4? ");
int x = 2;
int y = half(x);
float q = average(z g);
print_int(y);
print_float(2.7444);
print_float(q);
if(max_value_1 > max_value_2 || max_value_1 == max_value_2)
{
max(max_value_1);
}
else
{
max(max_value_2);
}
float a[] = {1.555, 3, 1.645, 178};
print_array(a, 4);
}
float average(float a)
{
return a / 2;
}
int times_two(int a)
{
return a * 2;
}
int half(int a)
{
return a / 2;
}
void print_int(int a)
{
printf("Value Exercise 1 = %i\n", a);
}
void print_float(float a)
{
printf("Value Exercise 2/3 = %.2f\n", a);
}
void max(float a)
{
printf("Value Exercise 4 = %.2f\n", a);
}
void print_array(float a, int b)
{
printf("Value Exercise 4 = %.2f\n", a);
}
For some other reason I get this error and really don't know how to fix them as I am new to ''functions'':
functions.c:37:17: error: passing 'float [4]' to parameter of incompatible type 'float'
print_array(a, 4);
^
functions.c:13:24: note: passing argument to parameter 'a' here
void print_array(float a, int b);
^
1 error generated.
CodePudding user response:
void print_array(float a, int b);
This line says that print_array
's first parameter is a float
.
float a[] = {1.555, 3, 1.645, 178};
print_array(a, 4);
This line passes an array as the first parameter to print_array
. This is inconsistent with the line shown previously that says the first parameter is a float
.
This is precisely what the error is telling you.
Your first step in fixing this would be to change this:
void print_array(float a, int b);
To something like:
void print_array(float a[], int b);
or
void print_array(float *a, int b);
CodePudding user response:
You are passing an object
of floats into a function parameter expecting a single float
value. Try redefining your print_array
function to accept an array of floats as argument, and have your code iterate through it in the function definition.
void print_array(float a[], int b){
//your code
}