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.
Related
The question is that I have to prompt the user to enter the base and height of a triangle as a float, pass it too a function where the function will get the area of the triangle, return it to main. the problem is that the output of the area is 0.000000.
its also giving me a warning
Severity Code Description Project File Line Suppression State
Warning C4477 'printf' : format string '%f' requires an argument of type 'double', but variadic argument 1 has type 'float (__cdecl *)(float,float)' line 38.
What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
float area(float base,float height);
int main()
{
float height;
printf("Enter an height: ");
scanf_s("%f", &height);
printf("Number = %f", height);
float base;
printf("Enter an base: ");
scanf_s("%f", &base);
printf("Number = %f", base);
area(height, base);
printf("area of triangle : %f\n", area);
return 0;
}
float area(float base, float height)
{
float half = .5;
float area = half * base * height;
return area;
}
Your primary issue is that you're passing a function (area), instead of the result of function invocation (area(height, base)). You need to store the result to a variable, then print that variable.
float computedArea = area(height, base);
printf("area of triangle : %f\n", computedArea);
Or you can just call the function, in-place, which work in this case, because it doesn't make the line too long:
printf("area of triangle : %f\n", area(height, base));
Here's how I would write this code:
#include <stdio.h>
#include <stdlib.h>
double area(double base,double height);
int main() {
printf("Enter the height: ");
double height;
scanf("%lf", &height);
printf("Height: %f\n", height);
printf("Enter the base: ");
double base;
scanf("%lf", &base);
printf("Base: %f\n", base);
double computedArea = area(height, base);
printf("Triangle Area: %f\n", computedArea);
return 0;
}
double area(double base, double height) {
return (base * height) / 2.0;
}
Change
area(height, base); // invoking a function without capturing its output
printf("area of triangle : %f\n", area); // area refers to the memory location where the function resides.
to
printf("area of triangle : %.2f\n", area(height, base));
// Directly passing the area output to printf. The '.2' specifies the precision you want
#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
After compiling, my GetInt function causes the printf statements within the function to be printed on the screen three times. I believe this was caused when I initialized all radius, base, and height to GetInt(void) but I see no other way of accurately initializing those variables. Please help!
#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)
{
int radius, base, height;
double triangleArea;
double circleArea;
radius = GetInt();
base = GetInt();
height = GetInt();
triangleArea = CalcTriangleArea(base, height);
circleArea = CalcCircleArea(radius);
return(0);
}
int GetInt(void)
{
int x;
{
printf("Please enter a radius: \n\n");
scanf("%d", &x);
printf("Please enter a base: \n\n");
scanf("%d", &x);
printf("Please enter a height: \n\n");
scanf("%d", &x);
}
return(x);
}
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("Area is %.4f \n\n", radius, circleArea = PI * pow(radius, 2));
return(0);
}
A rule of thumb is to avoid repeating yourself whereever possible and don't repeat yourself. Imagine you want to change from two new lines (\n\n) to three (\n\n\n)? You would need to make that change three times.
Looking at the bare bones of GetInt, you are printing a prompt, two new lines, get a value and returning it. Thus, we can write the new function like this:
void getInt(char* prompt)
{
int x, numberOfConversions; // numConversions is the number of int's read from the keyboard buffer
printf("%s: \n\n", prompt);
numberOfConversions = scanf("%d", &x);
while (numberOfConversions != 1) // while the user did not enter a number
{
printf("Please enter a number: ");
numberOfConversions = scanf("%d", &x)"
}
return x; // Always returns a valid number
}
GetInt asks for, and reads, 3 distinct values, yet returns only the last one, every time it is called.
I think what you really want is to have GetInt ask for and return just 1 value, either passing it the prompt to print or printing it before calling it.
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 would just like a push in the right direction here with my homework assignment. Here is the question:
(1) Write a C function called input which returns void, this
function prompts the user for input of
two integers followed by a double
precision value. This function reads
these values from the keyboard and
finds the product of the two integers
entered. The function uses call by
reference to communicate the values of
the three values read and the product
calculated back to the main program.
The main program then prints the
three values read and the product
calculated. Provide test results for
the input: 3 5 23.5. Do not use arrays
or global variables in your program.
And here is my code:
#include <stdio.h>
#include <stdlib.h>
void input(int *day, int *month, double *k, double *pro);
int main(void){
int i,j;
double k, pro;
input(&i, &j, &k, &pro);
printf("%f\n", pro);
return 0;
}
void input(int *i, int *j, double *k, double *pro){
int x,y;
double z;
double product;
scanf("%d", &x);
scanf("%d", &y);
scanf("%f", &z);
*pro += (x * y * z);
}
I can't figure out how to reference the variables with pointers really, it is just not working out for me.
Any help would be great!
You adding to pro but that is not initialized, you are not passing values back apart from pro. You store values into the addresses of variables passed in. In that case you need to dereference pointers to access/retrieve value, *i, and in your method use the passed addresses directly - then you don't need to take address of them again.
This works - I replaced double with float ... :
#include <stdio.h>
#include <stdlib.h>
void input(int *day, int *month, float *k, float *pro);
int main(void){
int i,j;
float k, pro;
i = j = k = pro = 0;
input(&i, &j, &k, &pro);
printf("%f\n", pro);
printf("%d : %d : %f\n", i,j,k);
return 0;
}
void input(int *i, int *j, float *k, float *pro){
scanf("%d", i);
scanf("%d", j);
scanf("%f", k);
printf("%d - %d - %f\n", *i,*j,*k);
*pro += (*i * *j * *k);
}
Output:
1
2
3.5
1 - 2 - 3.500000
7.000000
1 : 2 : 3.500000
You're almost there, but instead of making new variables x, y, and z, use the pointers you passed:
scanf("%d", i);
scanf("%d", j);
scanf("%f", k);
*pro += ((*i) * (*j) * (*k));
When reading the numbers in the input function you can make use of the pointers iptr, jptr, kptr and proptr to read the values directly into variables i,j and k declared in the main function as:
void input(int *iptr, int *jptr, double *kptr, double *proptr){
scanf("%d", iptr); // read directly into i using pointer to i.
scanf("%d", jptr);
scanf("%f", kptr);
*proptr = ( (*iptr) * (*jptr) ); // compute product and assign to pro.
}
*pro += (x * y * z);
This is going to break horribly. You're adding the product to whatever garbage happens to be in pro beforehand. You want to remove the +, i.e.:
*pro = (x * y * z);
What your program is not doing is setting the values of the input to i, j, and k.
Instead of using x,y and z, use the parameters instead.