I want to pass different amount of arguments by satisfying condition to the function. But the problem is the arguments have to be the same amount of parameter of a function.In every condtion I have different variables value which I want to pass as arguments. How can avoid this and successfully execute my code.
#include<stdio.h>
float file_w(float root1,float root2, float real,float imag)
{
FILE *fileWrite;
fileWrite= fopen("fileNames.txt", "a+");
if(root2==NULL && real==NULL && imag==NULL){
fprintf(fileWrite,"%.2f",root1);
fclose(fileWrite);
}
}
float file_r()
{
system("cls");
printf("\n\n\n\t\t\t\tCalculation History\n\n\t\t\t\t");
FILE *file;
char c;
file=fopen("fileName.txt","r");
if(file==NULL)
{
printf("file not found");
}
else
{
while(!feof(file))
{
c=fgetc(file);
printf("%c",c);
}
fclose(file);
printf("\n");
system("Pause");
main();
}
}
int main(){
double a, b, c, discriminant, root1, root2, realPart, imagPart;
int opt;
printf("Enter coefficients a, b and c: \n");
scanf("%lf", &a);
scanf("%lf",&b);
scanf("%lf",&c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("\n\t\t\t\troot1 = %.2lf and root2 = %.2lf\n\n\t\t\t\t", root1, root2);
file_w(root1,root2);
}
else if (discriminant == 0)
{
root1 = root2 = -b / (2 * a);
printf("\n\t\t\t\troot1 = root2 = %.2lf\n\n\t\t\t\t", root1);
file_w(root1);
}
else
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("\n\t\t\t\troot1 = %.2lf + %.2lfi and root2 = %.2f - %.2fi\n\n\t\t\t\t", realPart, imagPart, realPart, imagPart);
file_w(realPart,imagPart);
}
return 0;
}
Variable Length Argument in C
Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.
Sum of given numbers.
Minimum of given numbers.
and many more.
Variable number of arguments are represented by three dotes (…)
For example:
#include <stdio.h>
#include <stdarg.h>
double average(int num,...) {
va_list valist;
double sum = 0.0;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++) {
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);
return sum/num;
}
int main() {
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
Related
I have a problem with my code...
I want to input N numbers, for example if my N is 4 I want to calculate 1 2 3 4 with 10 20 30 40.
(1 and 10, 2 and 20 etc. )
But my program calculates 1 and 2, 3 and 4, etc.
So what can I do that my array can calculate the input piece by piece.
(I want to keep the on Value and on reference Pointer for the calculate sub-programm)
Code:
#define N 4
#include<stdio.h>
void KeyInput(double Input1[N]);
void KeyOutput(double Add[N], double Sub[N], double Mult[N], double Div[N]);
void calculate(double Input1[N], double Input2[N], double (*Add)[N],
double (*Sub)[N], double (*Mult)[N], double (*Div)[N]);
int main() {
int i;
double Input1[N], Input2[N], Add[N], Sub[N], Mult[N],
Div[N];
for (i = 0; i < N; i++) {
KeyInput(Input1);
KeyInput(Input2);
calculate(Input1, Input2, &Add, &Sub, &Mult, &Div);
KeyOutput(Add, Sub, Mult, Div);
}
return 0;
}
void KeyInput(double Input1[N]) {
fflush(stdout);
scanf("%lf", &Input1[N]);
}
void calculate(double Input1[N], double Input2[N], double (*Add)[N],
double (*Sub)[N], double (*Mult)[N], double (*Div)[N]) {
(*Add)[N] = Input1[N] + Input2[N];
(*Sub)[N] = Input1[N] - Input2[N];
(*Mult)[N] = Input1[N] * Input2[N];
(*Div)[N] = Input1[N] / Input2[N];
}
void KeyOutput(double Add[N], double Sub[N], double Mult[N], double Div[N]) {
printf("Summe: %lf \t", Add[N]);
printf("Differenz: %lf \t", Sub[N]);
printf("Produkt: %lf \t", Mult[N]);
printf("Quotient: %lf \n", Div[N]);
}
I've simplified and wrangled your code into a more conventional C form, where what you end up with is:
#include<stdio.h>
double key_input() {
double input;
fflush(stdout);
scanf("%lf", &input);
return input;
}
void calculate(double input1, double input2, double *add,
double *sub, double *mult, double *div) {
*add = input1 + input2;
*sub = input1 - input2;
*mult = input1 * input2;
*div = input1 / input2;
}
void key_output(double add, double sub, double mult, double div) {
printf("Summe: %lf \t", add);
printf("Differenz: %lf \t", sub);
printf("Produkt: %lf \t", mult);
printf("Quotient: %lf \n", div);
}
int main() {
int i;
for (i = 0; i < 4; i++) {
// Where practical just return values
double input1 = key_input();
double input2 = key_input();
double add, sub, mult, div;
calculate(input1, input2, &add, &sub, &mult, &div);
key_output(add, sub, mult, div);
}
return 0;
}
Once all the extraneous stuff, like the perplexing [N] stuff, is removed it's actually pretty straight-forward.
If you need to calculate multiple values in parallel you're going to need to explain in more detail what your intent is here. The original code is not set up to support that.
Notes here:
Use simple variable names like input instead of Input.
Don't use arrays unless your data is necessarily in array form.
Avoid extra syntax whenever possible. (*x) = y can be reduced to *x = y.
Define your functions before you use them to avoid having to declare and define separately.
So I am very new to C programming and I am stuck.
I am writing some code that reads certain data from a file (defined by my read_file function). One of my tasks was to also covert the distance between 2 given points (as seen by void distance) and convert that to radians (as seen by toRadian).
The issue however lies on line 48 (highlighted in the code), where I am getting
"error: expected expression
chord_length = pow(sin(toRadian(lat_2 - LAT_1)/2) + cos(toRadian
program.c:6:15: note: expanded from macro 'LAT_1'
define LAT_1 −37.798185"
What Have I done wrong? I just can't work it out.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LAT_1 -78.98214
#define LONG_1 -7.31600
#define R_PI 3.14159
#define DEGREES 180
int read_file(int i);
void toRadian(double theta);
void distance(double d);
int main()
{
int i = 0;
return read_file(i);
}
void toRadian(double theta)
{
double x = 0;
x = R_PI/DEGREES;
}
void distance(double d)
{
/* This function is designed to calculate the distance between the check-in
POI and the reference point provided*/
double dist, angle_distance, chord_length;
char *lat_2, *long_2;
char length[256];
char *token[6];
if (fgets(length, 256, stdin) != NULL)
{
token[0] = strtok(length, " ");
int i = 0;
double dist;
for (i = 1; i < 6; i++)
{
lat_2 = token[1];
long_2 = token[2];
}
chord_length = pow(sin(toRadian(lat_2 - LAT_1)/2) + cos(toRadian
(LAT_1)) * cos(toRadian(lat_2)) * pow(sin(toRadian(long_2 -
LONG_1))));
angle_distance = 2 * atan2(sqrt(chrod_length), sqrt(1 - cord_length));
dist = 6371 * angle_dist;
}
int read_file(int i)
{
/* This function takes the data from the input file,reading and printing the
User ID, Location (longitude and latitude), Date, Time, and Distance*/
char length[256];
char *token[6];
if (fgets(length, 256, stdin) != NULL)
{
token[0] = strtok(length, " ");
int i = 0;
double dist;
for (i = 1; i < 6; i++)
token[i] = strtok(NULL, " "); /*C programming is fun*/
printf("Stage 1\n==========\n");
printf("User: #%s\n", token[0]);
printf("Location: <%s, %s>\n", token[1], token[2]);
printf("Date: %s\n", token[3]);
printf("Time: %s\n", token[4]);
printf("Distance to reference: %2.2f\n", distance(dist));
}
else
{
printf("Error opening file. Check file and try again.");
exit(EXIT_FAILURE);
}
return 0;
}
You are subtracting a float from a pointer (lat_2 - LAT_1). This doesn't make any sense.
Also your passing it to toRadian() that takes a double and return nothing... it's all wrong
This is a somewhat corrected version of your program. It compiles almost with no errors.
Read carefully the comments starting with ***.
Probably there are more errors, but it's a start.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LAT_1 -78.98214
#define LONG_1 -7.31600
#define R_PI 3.14159 // *** correct and put PI with more decimals
#define DEGREES 180
int read_file(int i);
double toRadian(double theta); // *** correct declaration
double distance(double d); // *** correct declaration
int main()
{
int i = 0;
return read_file(i);
}
double toRadian(double theta)
{
double x; // *** no need to initialize with 0
x = R_PI / DEGREES; // *** something is missing here: up to to find what
// Hint: you need to use the theta parameter
return x;
}
double distance(double d) // ** correct prototype
{
/* This function is designed to calculate the distance between the check-in
POI and the reference point provided*/
double dist, angle_distance, chord_length;
double lat_2, long_2; // *** double here
char length[256];
char* token[6];
if (fgets(length, 256, stdin) != NULL)
{
token[0] = strtok(length, " ");
int i = 0;
double dist;
for (i = 1; i < 6; i++) // *** what's the purpose of this for loop???
{
lat_2 = atof(token[1]); // *** using atof here
long_2 = atof(token[2]);
}
chord_length = pow(sin(toRadian(lat_2 - LAT_1) / 2) + cos(toRadian
(LAT_1)) * cos(toRadian(lat_2)) * pow(sin(toRadian(long_2 -
LONG_1)))); // *** no idea what the formula should be , but pow needs 2 arguments
angle_distance = 2 * atan2(sqrt(chord_length), sqrt(1 - chord_length)); // *** using chord_length
dist = 6371 * angle_distance; // *** using angle_distance
return dist; // *** the function must return something.
}
} // *** this } was missing
int read_file(int i) // *** what's the purpose if the i parameter?
{
/* This function takes the data from the input file,reading and printing the
User ID, Location (longitude and latitude), Date, Time, and Distance*/
char length[256];
char* token[6];
if (fgets(length, 256, stdin) != NULL)
{
token[0] = strtok(length, " ");
int i = 0;
double dist;
for (i = 1; i < 6; i++)
token[i] = strtok(NULL, " "); /*C programming is fun*/
printf("Stage 1\n==========\n");
printf("User: #%s\n", token[0]);
printf("Location: <%s, %s>\n", token[1], token[2]);
printf("Date: %s\n", token[3]);
printf("Time: %s\n", token[4]);
printf("Distance to reference: %2.2f\n", distance(dist));
}
else
{
printf("Error opening file. Check file and try again.");
exit(EXIT_FAILURE);
}
return 0;
}
I have to use prototype poly float to compute f(x)=5x^2+12.55x+0.75. I have error every time I run this code because poly is not used. Any help will be good and any tips for prototypes too.
#include<stdio.h>
float poly(float x)
{
return 1;
}
int main()
{
float b, c, a;
printf("Podaj x=");
a = scanf("%f", &b);
c = 5 * b * b + 12.55 * b + 0.75;
if(a<1)
{
printf("Incorrect input");
return 1;
}else
{
printf("Wynik: %.2f", c);
return 0;
}
}
Change poly to:
float poly(float x)
{
return 5*x*x + 12.55*x + .75;
}
In main, you can use the function:
print("poly(%g) = %g.\n", b, poly(b));
I have to write a code for the c language for class but I'm getting this errors because the code is not returning the value correctly for some reason that I don't understand at all.
Requirements:
Tickets for the amusement park for the day cost $30.00 per adult, and $12.00 per child. There is also a 10% discount if more than 10 tickets are ordered in total.
Given two integer variables, num_adults, and num_children, calculate the total cost for amusement park admission for the day and store it in double variable total_cost.
my code: (you can assume every variable has been properly initialized. )
if (num_adults + num_children > 10)
{
total_cost =((30.00 * num_adults) + (12.00 * num_children)) - (0.10 * ((30.00 * num_adults) + (12.00 * num_children)));
printf("%d\n", total_cost);
}
else
{
total_cost=((30.00 * num_adults) + (12.00 * num_children));
printf("%d\n", total_cost);
}
Here's my best guess: You want to output it not as an integer (%d) but as a float %f
so do this:
printf("%.2f\n", total_cost);
#include <stdio.h>
int total_tickets(int c, int a)
{
return (c + a);
}
float total_cost(int c, int a)
{
return ((12.00 * c) + (30.00 * a));
}
float discounted_cost(int c, int a)
{
return (total_cost(c, a) * 0.9);
}
float actual_cost(int c, int a)
{
if(total_tickets(c, a) < 10)
{
return (total_cost(c, a));
}
else
{
return (discounted_cost(c, a));
}
}
int main(void) {
int c, a;
c = 2; a = 2;
printf("%.2f\n", actual_cost(c, a));
c = 5; a = 5;
printf("%.2f\n", actual_cost(c, a));
return 0;
}
I have written a small piece of code to calculate quadratic equations, but if the discriminant is negative, i wanted it to write that there are no real numerical values for this quadratic equation.
To make this happen, I had to call a function with a fourth parameter of 0, which i think , i have no idea why, would be a bad programming practice ? Is it the case or am i just being too picky of my code ? Thank you. (The reason I'm asking this is because i dont want to pick up some bad habits early on in my programming 'career').
Here's the code.
#include <stdio.h>
#include <math.h>
#include <string.h>
double quadratic_equation(double a, double b, double c, double d);
int main(void)
{
char command[20];
int i;
printf("Enter your command: ");
fgets(command, 20, stdin);
for (i = 0; i < 20; i++) {
if (command[i] == '\n') {
command[i] = '\0';
break;
}
}
if (strcmp(command, "quadratic equation") == 0) {
double a, b, c, x;
printf("Enter A: ");
scanf("%lf", &a);
printf("Enter B: ");
scanf("%lf", &b);
printf("Enter C: ");
scanf("%lf", &c);
x = quadratic_equation(a, b, c, 0); // THIS PIECE HERE MIGHT BE BAD PRACITCE ?
if (x == 0) {
printf("There are no real numerical values to this quadratic equation.");
}
else {
printf("------------\n");
printf("x1 = %.2f\n", quadratic_equation(a, b, c, 1));
printf("x2 = %.2f", quadratic_equation(a, b, c, -1));
}
}
return 0;
}
double quadratic_equation(double a, double b, double c, double d) {
double discriminant, x, insideroot;
insideroot = ((b*b) - (4*a*c));
if (insideroot < 0) {
return 0;
}
discriminant = sqrt(insideroot);
x = (-b + (d * discriminant)) / (2 * a);
return x;
}
Thank you very much for your help :d !
This certainly is bad practice. Since the roots of a formula a, b, and c an be any double you do need some sort of passing.
I would suggest a parameter that is a pointer to an int. If the pointer is NULL it is ignored, otherwise it will be set to 1 or 0 depending whether a real root exists:
double quadratic_equation(double a, double b, double c, int *root_exists) {
double discriminant;
discriminant = ((b*b) - (4*a*c));
if (discriminant < 0) {
if (root_exists != NULL) *root_exists = 0;
return 0.0;
}
x = (-b + sqrt(discriminant)) / (2 * a);
if (root_exists != NULL) *root_exists = 1;
return x;
}
A more rigorous approach is this:
typedef struct {
int num_roots;
double roots[2];
} quadratic_roots_t;
quadratic_roots_t quadratic_equation(double a, double b, double c) {
quadratic_roots_t roots;
double d;
d = b*b - 4*a*c;
if (d < 0.0) {
roots.num_roots = 0;
} else if (d == 0.0) {
roots.num_roots = 1;
roots.roots[0] = -b / (2 * a);
} else {
roots.num_roots = 2;
roots.roots[0] = (-b - sqrt(d)) / (2 * a);
roots.roots[1] = (-b + sqrt(d)) / (2 * a);
}
return roots;
}
I'd say it's not great to do. What you could do is something like this:
int quadratic_equation(double a, double b, double c, double *root_a, double *root_b) {
double discriminant = ((b*b) - (4*a*c));
if (discriminant < 0) {
return -1;
}
if (root_a != NULL) {
*root_a = (-b + sqrt(discriminant)) / (2 * a);
}
if (root_b != NULL) {
*root_b = (-b - sqrt(discriminant)) / (2 * a);
}
return 0;
}
Then you could call that like so:
double root_a;
double root_b;
int ok = quadratic_equation(a, b, c, &root_a, &root_b);
if (ok < 0) {
// It wasn't OK. Print out an error.
} else {
// It was OK. Print out the results.
}
Note that you should also check other error cases in the function and return -1 for them as well. E.g. a being zero.
Consider using the return value to indicate whether everything worked, and passing an array to the function to receive the return values:
enum QE_Status { QE_OK = 0, QE_NON_QUADRATIC, QE_COMPLEX_ROOTS, QE_NULL_POINTER };
enum QE_Status quadratic_equation(double a, double b, double c, double *r)
{
double discriminant;
if (r == 0)
return QE_NULL_POINTER;
if (a == 0.0)
return QE_NON_QUADRATIC;
discriminant = (b * b) - (4 * a * c);
if (discriminant < 0)
return QE_COMPLEX_ROOTS;
discriminant = sqrt(discriminant);
r[0] = (-b + discriminant) / (2 * a);
r[1] = (-b - discriminant) / (2 * a);
return QE_OK;
}
You can extend the system to handle numerical instability (because b*b is almost equal to 4*a*c, or because a is very small, etc).
The calling code can then be:
double a, b, c, x[2];
if (quadratic_equation(a, b, c, x))
...oops, something went wrong...
Or:
switch (quadratic_equation(a, b, c, x))
{
case QE_OK:
...print or use results in x...
break;
case QE_NON_QUADRATIC:
case QE_COMPLEX_ROOTS:
...print appropriate error message about user's data...
break;
case QE_NULL_POINTER:
...Oops - programming error...
break;
}
I would certainly call it bad practice because the code is very unclear.
Firstly, you are calling the function three times, when once should be enough.
I'd consider returning/filling a list in your quadratic_equation() function instead of returning the roots one by one.
This would also allow you to determine if there are real roots -- if there aren't, just return an empty list.
As a whole, this would be much more elegant than your current solution, and it would eliminate the need for checking whether there are any solutions beforehand.