#include <stdio.h>
#include <math.h>
#define G 9.81
typedef struct
{
double weight;
double drag;
double time;
} USER_INPUT;
double calculateVelocity(USER_INPUT);
int main(int argc, char **argv)
{
USER_INPUT userInput;
double velocity;
printf("Please enter weight, drag and time: ");
scanf("%lf %lf %lf", &userInput.weight, &userInput.drag, &userInput.time);
velocity = calculateVelocity(userInput);
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", &userInput.time, &userInput.weight, &userInput.drag, velocity);
return 0;
}
double calculateVelocity(USER_INPUT data)
{
double velocity;
// TODO compute velocity
return velocity;
}
In the main function, I want to display the result.
How can I print variables defined in the structure?
I tried %f, which returns 0.000000, and %d returns a random number.
You are doing mistake while printing,
Please note '&' is used to get the address of any variable, not the value.So when you are printing:
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", &userInput.time, &userInput.weight, &userInput.drag, velocity);
you are actually printing the adderss of variables:
&userInput.time (address of (userInput.time)),
&userInput.weight(address of (userInput.weight)), &userInput.drag (address of (userInput.drag)).
You want to print their values, not address, hence remove '&' while printing:
ie;
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", userInput.time, userInput.weight, userInput.drag, velocity);
Well not sure about all the physics or which equation so I kind of faked that, but I got your program to compile and run so it should be pretty easy for you to fix it from here. Feel free to ask questions about the pointer stuff and why addresses were and weren't used in different places.
#include <stdio.h>
#include <math.h>
#define G 9.81
#define P 1.00 // ?
#define A 1.00 // ?
typedef struct {
double weight;
double drag;
double time;
} userInput_t;
double calculateVelocity(userInput_t *); // Terminal velocity?
double calculateVelocity(userInput_t *data) {
return sqrt((2 * data->weight * G)/(P * A * data->drag));
}
int main(void) {
userInput_t userInput;
printf("Please enter weight, drag and time: ");
scanf("%lf %lf %lf", &userInput.weight, &userInput.drag, &userInput.time);
double velocity = calculateVelocity(&userInput);
printf("\nAt t = %f, the parachutist with weight %f kg\n"
"and a drag coefficient %f kg/s\n"
"will have a velocity of %f m/s^2\n",
userInput.time, userInput.weight, userInput.drag, velocity);
}
int printf(const char *format, ...);
is NOT
int scanf(const char *format, ...);
scanf works with memory addresses of variables, while printf with variables itselves.
It's UB trying to
printf ("%d", memory_addres_of_variable);
because the right way to print memory addresses is with %zu starting from C99 and later, and %lu with ANSI C 90.
That's why you aree seeing a random number.
The issue is not related to struct. You are passing addresses of variables instead of their values to printf. So the solution is simple: Remove the & before variable names in the printf call.
This is a common mistake: scanf needs the addresses of variables to be able to alter their values, while printf just takes the values. Unfortunately even the prototypes do not make it evident:
int printf(const char *format, ...);
int scanf(const char *format, ...);
And you need to use %f for double variables (derived from the type called float), %d is used for int (decimal).
The result:
printf("At t = %f , the parachutist with weight %f kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", userInput.time, userInput.weight, userInput.drag, velocity);
References:
http://en.cppreference.com/w/cpp/io/c/fprintf
http://en.cppreference.com/w/c/io/fscanf
Related
I've tried to build a simple calculator for physics force experiments.
//
// main.c
#include <stdio.h>
int main() {
char name[20];
int month,date;
int difference_percentage1, difference_percentage2, difference_percentage3;
double force1, force2, force3;
scanf("%s", name);
scanf("%d %d", &month, &date);
scanf("%lf %lf %lf", &force1, &force2, &force3);
double Favg=(force1 + force2 + force3)/3.000;
puts(name);
difference_percentage1=100*(force1-Favg)/Favg;
difference_percentage2=100*(force2-Favg)/Favg;
difference_percentage3=100*(force3-Favg)/Favg;
printf("%d %d %d\n", difference_percentage1, difference_percentage2, difference_percentage3);
getchar();
return 0;
}
The calculate doesn't match what I've typed for scanf().
The o's of the % mark for the %f look a bit larger to me than for the %d, so my guess is that you used the wrong % for the %f format specifier which isn't recognized by the compiler; it interprets the double value as int.
Edit: one more reason to post text instead of a screenshot of the code! (o;
Edit2: Yup, your % mark in %f is actually a "EF BC 85" in hex but should be "25"
I am very new to C, and while working on a project which requires pulling an indeterminate amount of values from the console, I am finding that it is not pulling the correct values. It seems like addresses, which I believe means it is a pointer issue, but I can't seem to find it.
int getVals(int degree){
double sum;
double x;
double coefs[degree];
for(int counter = 0; counter<=degree; counter = counter+1){
double nxt;
scanf(" %d", &nxt);
coefs[counter] = nxt;
printf("coefs[%d] = %d\n", counter, coefs[counter]);
}
printf(" x ? ");
scanf(" %d", &x);
printf("degree %d x %d\n", degree, x);
sum = poly(x, degree, coefs);
printf ("polynomial evaluate to: %lf\n", sum);
int newDegree;
scanf(" %d", &newDegree);
degree = newDegree;
if(degree>-1){
getVals(degree);
}
else
return degree;
}
Note: poly returns a double result of the evaluated polynomial
I am getting the following infinite loop after entering a degree of 1 and a coefficient of 1.5. It does not allow me to enter an x.
Infinite loop
In scanf(" %d", &newDegree); you should use the "%lf" format specifier (since your values is a double, not an int). Change the format specifier in all your calls to scanf() and "%f" in calls to printf().
Please refer to the documentation at this links printf(3), scanf(3).
I was trying to calculate the area of both a triangle and a circle using 3 separate user defined functions within main. After compiling, the GetInt function worked properly but the other two functions' calculations are not printing on the screen accurately for my c program on Microsoft Visual Studio 2013. What am i doing wrong?
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.14159
#include <stdio.h>
#include <math.h>
int GetInt(void);
double CalcTriangleArea(int base, int height);
double CalcCircleArea(int radius);
int main(void)
{
printf("%d", GetInt());
printf("%f", CalcTriangleArea);
printf("%f", CalcCircleArea);
return(0);
}
int GetInt(void)
{
int radius, base, height;
printf("What is the radius of the circle? \n\n");
scanf("%d", &radius);
printf("What is the base of the triangle? \n\n");
scanf("%d", &base);
printf("\nthe height of the triangle? \n\n");
scanf("%d", &height);
return (radius, base, height);
}
double CalcTriangleArea(int base, int height)
{
double triangleArea;
printf("Triangle area is %.2f \n\n", triangleArea = .5*base*height);
return(0);
}
double CalcCircleArea(int radius)
{
double circleArea;
printf("Circle area is %.4f \n\n", circleArea = PI * pow(radius, 2));
return(0);
}
CalcTriangleArea Is not calling the function, it's using the functions address. Try CalcTriangleArea()
edit: Just noticed CalcTriangleArea takes parameters - you'll need to pass those in too.
edit: And how do you think you can return 3 values?
For CalcTriangleArea and CalcCircleArea there is no need to have the printf's in main if you're printing the results in your functions. You could simply call them in main like so:
GetInt();
CalcTriangleArea(base, height);
Also, if this is the approach you are taking (printing results in the function and returning 0), your functions could be declared like so:
void myFunction(int arg1, int arg2)
Since your are not returning anything that you are using, using a void type allows you to have a function without an explicit return.
I am working in c after a long time.Here i have to achieve three functionality which includes
get a number and show half
2.Get the square of the number
3.Get two number and show their summation and sabtraction.
I am using devC++ and when i compile the code i get the error i mentioned in the title which conflict type if squareInput.What is wrong here:
#include<stdio.h>
#include<conio.h>
int main(){
float x;
printf("enter a number\n");
scanf("%f",&x);
//TASK 1 : display half of the number
pirntf("half of x is = %.3f",x);
//TASK 2 : square of number
squareInput(x); //call square function from here
// TASK 3 : get two numbers and display both summation and sabtraction
float num1,num2; // declare two floating number( floating numbers can hold decimal point numbers
printf("enter num1 \n");
scanf("num1 is =%f",&num1);
printf("enter num2 \n");
scanf("num2 is =%f",num2);
calculate(num1,num2);// call calculate function
getch();
}
float squareInput(float input){
float square=input*input;
printf("\n square of the number is %.3f \n",square);
return 0;
}
float calculate(float num1,float num2){
//summation
float summation= num1+num2; // declare antoher variable called summation to hold the sum
//sabtraction
float sabtraction=num1-num2;
printf("summation is %.2f \n",summation);
printf("sabtraction is %.2f \n",sabtraction);
return 0;
}
Things will go wrong without prototypes. Add
float squareInput(float input);
float calculate(float num1,float num2);
in front of int main().
If you don't declare a function before it's called, the compiler assumes it as a int-returning function. However, squareInput() return float, so the compiler(or linker, maybe) complains to you.
Also note that definitions are declarations(but not vice versa, obviously), so moving the definitions of squareInput() and calculate() in front of where they are called works too.
At the time you call squareInput and calculate, they haven't been defined yet. So C assumes an implicit declaration of int squareInput() and int calculate(). These implicit declarations conflict with the definitions of these functions.
You can fix this by either adding declarations for each of these functions before main:
float squareInput(float input);
float calculate(float num1,float num2);
Or by simply moving the functions in their entirety before main.
Be sure to add prototypes when you use a function. That way you do not need to worry too much about the order in which you call them.
Also try to separate your problems into smaller bits if you can. A comment like TAKS1 shows you that you actually want a function with that name.
#include <stdio.h>
//prototypes
void AskUserForOneNumer(float * number, const char * question );
void TASK_1(float x);
void TASK_2(float x);
void TASK_3(float a, float b);
int main()
{
float x, a, b;
AskUserForOneNumer(&x, "enter x");
AskUserForOneNumer(&a, "enter a");
AskUserForOneNumer(&b, "enter b");
TASK_1(x);
TASK_2(x);
TASK_3(a, b);
}
void TASK_1(float x)
{
printf("x = %g\n", x);
printf("0.5 * x = %g\n", 0.5 * x);
}
void TASK_2(float x)
{
printf("x = %g\n", x);
printf("x * x = %g\n", x * x);
}
void TASK_3(float a, float b)
{
printf("a = %g\n", a);
printf("b = %g\n", b);
printf("a + b = %g\n", a + b);
printf("a - b = %g\n", a - b);
}
void AskUserForOneNumer(float * number, const char * question)
{
float x;
printf("%s\n", question);
scanf("%f", &x);
printf("your input was %g\n", x);
*number = x;
}
I'm doing an exercise in C that has me inputting data into a struct and then manipulating it in a separate function. But when the program comes to the line where the actual math is being done, I get an error about a called object not being a function.
Here's the exact error:
p1s2.c:70:106: error: called object '(vectorArray + (sizetype)((unsigned int)i * 32u))->y * (vectorArray + (sizetype)((unsigned int)i * 32u))->y' is not a function
I'll apologize in advance for the code, this is a work-in-progress file so it isn't very clean.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Structure declaration.
struct vector {
double x; //X-coordinate for vector
double y; //Y-coordinate for vector
double z; //Z-Coordinate for vector
double length; //Length. Calculations will go here.
};
int howLong(struct vector *x);
int main(void)
{
int arraySize;
int i;
int vectorNum=1;
int retval; //Watch for counter in howLong.
int scanval; //Error checking for coordinates input (scanf statement)
printf("How many vectors would you like to calculate length for?\n");
scanf("%d", &arraySize);
//Allocate memory to struct.
struct vector *vectorArray = malloc(arraySize*sizeof(double));
printf("You will now enter the coordinates for %d vectors. \n", arraySize);
//Input loop.
for(i=0; i<=arraySize; i++){
printf("Please enter the X, Y, Z coordinates for vector %d. \n", vectorNum);
printf("Please separate the coordinates with spaces. \n");
int scanval; //Error checking: Scanval should be equal to three.
//scanf takes user input, converts to long float.
scanval=(scanf("%lf %lf %lf", &vectorArray[i].x, &vectorArray[i].y, &vectorArray[i].z));
if(scanval !=3) {
printf("You can't follow directions. That's too bad. \n");
exit(0);
}
//Print input back to user.
printf("Vector Number %d: %lf %lf %lf \n", vectorNum, vectorArray[i].x, vectorArray[i].y, vectorArray[i].z);
//Increment counters.
vectorNum++;
i++;
}
for(i=0; i<=arraySize; i++){
vectorArray[i].length=howLong(vectorArray);
i++;
}
}
Here's the external function howLong:
int howLong(struct vector *vectorArray)
{ //Function gets the struct and coordinate values, calculates length and writes to struct.
int i;
int vectorNum=1;
printf("Calculating vector length. \n");
//Math.
vectorArray[i].length = sqrt((vectorArray[i].x * vectorArray[i].x)+(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z));
//Error occurs on the line directly above this comment. ^^
printf("Length of Vector Number %d: %lf \n", vectorNum, vectorArray[i].length);
return vectorArray[i].length;
}
I don't get it. At first I thought it had to do with function names, but the error persisted after I changed the function name to howLong. Any ideas?
Well, here:
(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z)
is missing a plus sign, between the two () parts.
In function howLong
((vectorArray[i].x * vectorArray[i].x)+(vectorArray[i].y * vectorArray[i].y)(vectorArray[i].z * vectorArray[i].z));
^operator is missing