My function aren't working after i called them - c

I've put an printf to check if the function works, but i cant figure out why it doesnt work.
The numbers are all correct in functions, but they dont get executed.
I am not sure why the function isn't working, i dont have much knowledge in C so if anyone could help me that would be much appreciated.
The program is supposed to calculate the odds of you passing the test, by calculating the odds of the people around in your class room.
Example:
P
NXNXNXNXN
ZNZNXXXXX
XNZXNNNZX
ZNXHXXXXZ
NNNNZNNXN
P - professor
Z - prepared student
N - unprepared student
X - an empty seat
H - Me
Input:
3 4
2 50
X X X X
Z H N X
Z N X X
Expected Output:
Sanse za prolaz su 62.50%
Output gotten:
Sanse za prolaz su -0.00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
///FUNKCIJA POSTOTAK
float fudaljenost(int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='Z')
{
Zx=i;
Zy=j;
udaljenostx=abs(Hx-Zx);///A
udaljenosty=abs(Hy-Zy);///B
printf("Z A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak+=90/(udaljenost*udaljenost);///POSTOTAK
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='N')
{
Nx=i;
Ny=j;
udaljenostx=abs(Hx-Nx);///A
udaljenosty=abs(Hy-Ny);///B
printf("N A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak-=30/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
///FUNKCIJA PROFESOR
float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
int Hx,Hy;
int Px,Py;
float udaljenostx=0,udaljenosty=0,udaljenost;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='P')
{
Px=i;
Py=j;
udaljenostx=abs(Hx-Px);///A
udaljenosty=abs(Hy-Py);///B
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak=strogost/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
int main()
{
int i=0,j=0;
int visina,sirina;
int prof;
float strogost;
float posto1,posto2,posto;
char Ucionica[50][50]={0};
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
scanf(" %d%d",&visina,&sirina);
scanf(" %d%f",&prof,&strogost);
///UPIS MATRICE
for(i=1;i<visina+1;i++)
{
for(j=0;j<sirina;j++)
{
scanf(" %c",&Ucionica[i][j]);
}
}
Ucionica[0][prof-1]='P';
posto1 = fudaljenost(visina,sirina,Ucionica);
posto2 = fprofesor(strogost,visina,sirina,Ucionica);
posto = posto1-posto2;
printf("Sanse za prolaz su %.2f",posto);
return 0;
}
Stackoverflow isnt allowing me to post this without adding more words, so im using this part of the text to add more words, sorry stackoverflow for going around the system like this but im kinda running out of time on this.

The current code passed cast on a main variable char Ucionica[50][50]={0} into a function that expects a prototype of float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina]).
From the context, it looks as if the [50],[50[ represent the largest possible input size, but the program will use only the first few rows/columnns (3, 4 in the example). Regardless of how much data will be used, the definition in the called functions should match the data size.
float fprofesor(float strogost,int visina, int sirina,char array[50][50]) { ... }
float fudaljenost(int visina, int sirina,char array[50][50]) { ... }
Side note, gcc -Wall flaggedd many warning on unused variables, but no warning in passing array with mismatch minor array size
Also, probably a good idea to '#define' the maximum size, instead of hardcoding 50 repeated times.

The functions were written wrong,
in
float fudaljenost(int visina, int sirina,char array[visina][sirina])
It wasn't the same size array as sent before[50][50]
The following will fix the problem:
float fudaljenost(int visina, int sirina,char array[50][50])
float fprofesor(float strogost,int visina, int sirina,char array[50][50])
Worth noting that it will be better to #define MAX_ARRAY_SIZE 50, and use MAX_ARRAY_SIZE instead of 50. This will make it easier to avoid error if the number will need to be changed, and will provide hint on what the 50 is.

Related

Determination of polynomials

I need help solving this task, if anyone had a similar problem it would help me a lot.
The task is:
Write a program that calculates the degree and polynomial p(x) for a given x.
For example:
Enter n:2 //degree of polynomial and function degree
Enter x:2
x^n=4
Enter coefficients of polynomial:
a[0]=1
a[1]=2
a[2]=3
P(x)=3*x^2 + 2*x^1 +1*x^0 = 17
I did it like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
/*
*/
typedef struct polynomial {
double coef[MAX];
} POLYNOMIAL;
double degree(double ,int );
double px(POLYNOMIAL ,double );
int main()
{
POLYNOMIAL p;
double x,pom;
int n;
printf("Enter degree (n>=0):");
scanf("%d",&n);
while(n<1 || n>MAX)
{
printf("Enter degree (n>=0):");
scanf("%d",&n);
}
printf("Enter x:");
scanf("%lf",&x);
pom=degree(x,n);
printf("%.2lf^%d =%lf",x,n,pom);
printf("\nEnter coefficients of polynomial :\n");
for(int i=0;i<=n;i++)
{
printf("a[%d]:",i);
scanf("%lf",&p.coef[i]);
}
return 0;
}
double degree(double x,int n)
{
double degree=1;
if(n==0)
{
return 1;
}
for(int i=1;i<=n;i++)
{
degree*=x;
}
return degree;
}
double px(POLYNOMIAL p,double x)
{
double sum=0;
for(int j=0;j<"I don't know what to put here";j++)
{
sum+=(double)p.coef[j]*degree(x,j);
}
printf("%lf",sum);
}
The problem arises when calculating polynomials, because I don't know what to put as a condition in the for loop, there should be j < of the length of the array entered, that is, of degree n,
but n cannot be used as a parameter in the px function? The task must be done with the structure and functions listed.
Thanks in advance !
If you are not allowed to pass n to the function, you can instead just loop to MAX and make sure that all unused coefficients are zero.
In other words, just initialize all elements of p to zero
POLYNOMIAL p = {.coef = {0} };
and let the loop be:
j < MAX
BTW: Notice that you need return sum in the function.
Further the function degree is pretty unnecessary. Consider this:
double px(POLYNOMIAL p,double x)
{
double sum=p.coef[0];
double d = x;
for(int j=1;j<MAX;j++)
{
sum+=(double)p.coef[j]*d;
d = d * x;
}
printf("%lf",sum);
return sum;
}

Function to calculate Pi in C

I'm trying to code a formula where the user inputs a number n to calculate Pi using Pi= n^2/(n-1)(n+1). But for some reason the output is wrong. I don't know if my math is wrong or there's something wrong with the function.
Here is the code :
#include <stdio.h>
#include <math.h>
double pi_array (int n)
{
int i;
double a;
if (n%2==0)
{
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
}
return a;
}
double pi_value (int n)
{
int i;
double pi;
for (i=0;i<=n;i++)
{
pi=pi_array(n);
}
return pi;
}
void main()
{
int n;
scanf("%d",&n);
printf ("%lf\n", pi_value(n));
}
Just like #Mat pointed out, in this part of your code:
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
It is doing the same computation again and again because n does not change its value. The answer pow(n,2)/((n-1)*(n+1)) remains the same even for all the iterations.
Also, on a side note, what formula are you using to calculate your answer? If you put n = 4, you get the value as 16/15 which equals 1.0667. For n = 5, the asnwer is 1.041667. They are clearly not equal to pi. I think thew formula might be wrong itself. You could post the question about the formula on MathStackExchange to get an idea of what the exact formula is, and then implement it in C later :).
Best.

Passing two arguments

I want to pass two arguments into void Dividing from void Assign_numbers and void Maximum. I have only learnt to pass one argument at a time. Can you please tell me what I have to do print out the following variables inside void Dividing. If it's possible, I don't want the format of my code to change drastically. Can you also show me an example, since I am a visual learner. Thanks
#include <stdlib.h>
#include <stdio.h>
#define Max 6
struct Numbers
{
double a,b,c,d,e,f;
};
void Maximum(double *ptr);
void Dividing(double Maximum, double *ptr);
void Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
Maximum((double*) &number);
Dividing((double*) &number);
}
void Maximum(double *ptr)
{
int i=0;
double Maximum = ptr[0];
for(i;i<Max;i++)
{
if(ptr[i]> Maximum)
{
Maximum = ptr[i];
}
}
Dividing(Maximum);
}
void Dividing(double Maximum, double *ptr)
{
printf("%.2f", Maximum);
printf("%.2f",ptr[3]);
}
int main()
{
Assign_numbers();
return 0;
}
Use array instead of struct - shwon here with reference example
Like Joachim Pileborg said. Don't use a struct as an array. In your case use a multidimensional array.
double[10][6] numbers;
You can easily iterate through such an array like so:
#include <stdio.h>
int main () {
/* an array with 2 rows and 6 columns*/
double numbers[2][6] = {
{45.78, 81.45, 56.69, 34.58, 23.57, 78.35},
{1,2,3,4,5, 6}
};
int i, j;
/* output each array element's value */
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 6; j++ ) {
printf("numbers[%d][%d] = %f\n", i,j, numbers[i][j] );
}
}
/* Output by reference */
for(i = 0; i < 2; i++){
for(j=0; j < 6; j++ ){
printf("numbers[%d][%d] = %f\n", i, j,*(*(numbers + i) + j));
}
}
return 0;
}
Why the current code fails
Now onto explaining how your code (does not) work and a little about how pointers work. First off:
Dividing(double Maximum, double* ptr);
Does not work in the way you think it does. "double Maximum" is a new double variable that works within the scope of Dividing and is not a variable retrieved from the function:
void Maximum(double *ptr);
If you already knew this, then you should know or at least have expected how poor the naming of your variables are(keep it lowerCamelCase).
Now lets get onto what you're trying to do. IMHO your code is completely broken unless I am noticeing something. In Assign_numbers() you want to call Dividing() using a pointer reference. In Maximum() you want to call Dividing() again, but this time sending only a value. It doesn't make it better that you have 2 separate different calls that each have one parameter. But the function has to have two parameters. Now in order to iterate through the variables in a struct - again this is not recommended and the bottom code only serves as an example.
struct Numbers
{
double a,b,c,d,e,f;
};
struct Numbers Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
return number;
}
int main()
{
struct Numbers number;
number = Assign_numbers(number);
double *value = &(number.a); //take address of the first element, since a pointer always counts upwards.
int i;
/*This loops through the addresses of the struct starting from the initial address in number.a and moves upwards 5 times and hopefully ends in number.f. Seriously bad way to construct arrays*/
/*Just try replacing sizeof(number) with sizeof(double). suddenly you get all kinds of weird values because you have ended up outside of the struct*/
/*Also note that this only works when all the datatypes in the struct have a size of 8 bytes(the size of double) */
for (i = 0; i < sizeof(number) / sizeof(double); i++){
printf("[%d]: %f\n",i, value[i]);
}
return 0;
}
New working code
With all that said. This is the closest I am going to to be able to make your code work since I have no idea what you're trying to accomplish:
#include <stdlib.h>
#include <stdio.h>
#define Max 6
struct Numbers
{
double a,b,c,d,e,f;
};
void Maximum(double *ptr);
void Dividing(double *ptr);
void Assign_numbers()
{
struct Numbers number;
number.a=45.78;
number.b=81.45;
number.c=56.69;
number.d=34.58;
number.e=23.57;
number.f=78.35;
Maximum(&number.a); //You need to parse the very first address of the struct. IN this case 'a'
Dividing(&number.a);
}
void Maximum(double *ptr)
{
int i=0;
double maximum = ptr[0];
for(i;i<Max;i++)
{
if(ptr[i]> maximum)
{
maximum = ptr[i];
}
}
printf("maximum: %f", maximum);
}
/*//removed the first parameter since it was not clear what it was for and you only had function calls to this function with one parameter */
void Dividing(double *ptr)
{
printf("%.2f",ptr[3]);
}
int main()
{
Assign_numbers();
return 0;
}

Find the highest number using another function

could everyone please help me what is wrong with my code or what is missing from my code...
We have this activity where we have to find the highest number using another function..
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int n1);
int main(int argc, char *argv[])
{
int i, num[10];
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num[i]));
getch();
}
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
When I input any number I always got 37..
int high (int n1); should be
int high (int *arr, int sz); /* You need to pass an array */
p("Highest Number: %d",high(num[i])); should be
p("Highest Number: %d",high(num, 10)); /* Passing array now, not one element */
int high() should be re-written as:
int high (int *arr, int sz)
{
int l, mx = INT_MIN;
for (l=0; l<sz; l++)
{
if (mx < arr[l])
{
/* Left as an excercise */
}
}
return mx;
}
As this is tagged c++, I would suggest using available C++ to find max in a range:
const int max = *std::max_element(&num[0], &num[10]); // #include <algorithm>
Well, I don't know if you still need an answer, but I corrected your code. Here are the mistakes I found
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
In this for-loop, there is the condition l<n1 and inside the for loop you have the statement if(n1 > l) which will never be attained because of l<n1. You said you were getting 37 each time, but I was getting 10 instead. This shows it was undefined behavior because no real value was returned. ( This code part really didn't mean any sense either as this function doesn't even try to find the largest number ).
Another issue I found is you have used getch() without including <conio.h> ( Also pointing out that <conio.h> is not standard in C++ )
Well, even though this question is tagged C++, since the code is completely c, I have made a fixed code in c. I've removed getch() in the code. So here is the code
#include<limits.h>
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int *n1,int lar); // now I have used *n1 to get the address of the array.
int main(int argc, char *argv[])
{
int i, num[10],lar=INT_MIN; // the variable lar is given the minimum value that can be held by an int
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num,lar)); // sending the entire array to the function by sending its address
}
int high (int *n1,int lar)
{
int l;
for (l=0; l<10; l++) // since the size you have taken for your array is 10, I have used 10 here. But if you don't know the size beforehand, pass the size as an argument to the function
{
if (n1[l] >lar ) // Well, this is the simple part
lar=n1[l]; // Simply assigning the largest value to lar
}
return lar; // Finally returning the value lar.
}
Well, hope this helps you.

Help implementing Least Squares algorithm in C [was: want to find the square root of an array]

the formula is pretty complicated. the numerator is num and the denominator is den, in the formula there is a root on the denominator so i have putted den in sqrrt() but sqrrt only accepts doubles
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define LEN 11
// for the following set of x and y find r by the formula ..
float sum(float arr[]);
void main(void)
{ int i;
float x[]={43.22,39.87,41.85,43.23,40.06,53.29,53.29,54.14,49.12,40.71,55.15};
float y[]={102.43,100.93,97.43,97.81,98.32,98.32,100.07,97.08,91.59,94.85,94.6};
float num,den[LEN],r[LEN],xy[LEN],x2[LEN],y2[LEN];
for(i=0;i<LEN;i++)
{
x2[i]=x[i]*x[i];
y2[i]=y[i]*y[i];
xy[i]=x[i]*y[i];
}
num=sum(xy)-sum(x)*sum(y);
for(i=0;i<LEN;i++)
{
den[i]=((LEN*sum(x2)-(sum(x))*(sum(x)))*(LEN*sum(y2))-(sum(y2))*(sum(y2)));
r[i]=num /sqrt(den); /*<----------the problem is here-----> */
}
printf("%f",r);
getch();
}
float sum(float arr[])
{
int i;
float total=0;
for(i=0;i<=LEN;i++)
{
total+=arr[i];
}
return total;
}
Out of sheer boredom I have fixed your code. It is still ugly and extremely inefficient but compiles and should work. I'll leave you or someone else to make it decent.
#include <stdio.h>
#include <math.h>
#define LEN 11
// for the following set of x and y find r by the formula ..
float sum(float arr[]);
int main(void)
{ int i;
float x[]={43.22,39.87,41.85,43.23,40.06,53.29,53.29,54.14,49.12,40.71,55.15};
float y[]={102.43,100.93,97.43,97.81,98.32,98.32,100.07,97.08,91.59,94.85,94.6};
float num,den,r[LEN],xy[LEN],x2[LEN],y2[LEN];
for(i=0;i<LEN;i++)
{
x2[i]=x[i]*x[i];
y2[i]=y[i]*y[i];
xy[i]=x[i]*y[i];
}
num=LEN*sum(xy)-sum(x)*sum(y);
den = (LEN*sum(x2)) - sum(x)*sum(x);
float alpha = sum(y)/LEN - (num/den)*sum(x)/LEN;
printf("beta = %f, alpha = %f\n", num/den, alpha);
for(i=0;i<LEN;i++)
{
float term = y[i] - alpha - (num/den)*x[i];
r[i] = (term*term);
printf("%f",r[i]);
}
}
float sum(float arr[])
{
int i;
float total=0;
for(i=0;i<=LEN;i++)
{
total+=arr[i];
}
return total;
}
To be consistent with the rest of the code, you should presumably be writing:
r[i] = num / sqrt(den[i]);
However, the calculation is not one I recognize. The body of the second loop is going to produce the same result for each value in den and therefore also in r, which is probably not what the question asked for.
You need to give the index den[i] at the denominator....instead in your code you have just passed the base address!
r[i]=num /sqrt(den[i]);
If this is what you want to achieve, which is quite unclear.

Resources