I have made a verry simple calculation prog to teach myself C. but i have an odd bug now and would like to ask some advice.
About an hour ago i also asked help here to get rid of global variables and got some suggestions (again thanks for that).
Now i have implemented those suggestions but when i now input a diameter in the calculation it returns with a verry large and odd number for al 3 functions.
And that number is the same for all 3 functions.
I don't understand where the function is getting that number from as i define the diameter variable in the cir_user_input() (input.c) first and only call it again in getRadius(float diameter) (circlefunctions.c). i have tried several things like pointers or make use of the EXTERN statement but that did not gave me the result that i wanted/expected. Hopefully someone can point me out on what i do wrong here or can suggest some documentation on how to solve this?
main.c
#include <stdio.h>
#include "menu/menu.h"
#include "circle/circlemenu.h"
#include "input/input.h"
int main(void)
{
while(1)
{
menu();
switch(menu_user_input())
{
case 1:
info_top();
cir_user_input();
info_bottom();
break;
case 2:
system("cls");
break;
case 3:
system("cls");
break;
case 8:
system("cls");
break;
case 9:
system("cls");
break;
case 0:
return(0);
default:
system("cls");
printf("\n **Wrong choice try again...**\n");
break;
}
}
return 0;
}
circlemenu.c
#include <stdio.h>
#include "circlemenu.h"
void info_top()
{
system("cls");
printf(" ----------------------------------------\n");
printf(" Typ the diameter of the circle: ");
}
void info_bottom(double diameter)
{
printf(" ----------------------------------------\n");
printf(" The radius = %f \n\n" , getRadius(diameter));
printf(" The surface = %f \n\n" , getSurface(diameter));
printf(" The outline = %f \n" , getOutline(diameter));
printf(" ----------------------------------------\n");
}
circlefunctions.c
#include "circlefunctions.h"
#include "../input/input.h"
#define PI 3.14
double getRadius(float diameter)
{
double radius = diameter / 2;
return radius;
}
double getSurface(float diameter){
double radius = getRadius(diameter);
return PI * (radius * radius);
}
double getOutline(float diameter){
double radius = getRadius(diameter);
return 2 * PI * radius;
}
input.c
#include <stdio.h>
#include "input.h"
int menu_user_input()
{
int number;
scanf(" %d", &number);
return number;
}
float cir_user_input()
{
float diameter;
scanf(" %e", &diameter);
return diameter;
}
edit
I forgot to mention that im verry new to programming and im just trying to learn it myself. Some things may seem to be odd but im just trying to tackle and understand one problem at the time.
info_bottom(); you should pass diameter as argument i.e. info_bottom(diameter);
Adding to #JerryGoyal 's answer, In your main.c
case 1:
info_top();
cir_user_input();
info_bottom(); // here
break;
In the commented line, you need to give info_bottom() an argument when you call it. Something like info_bottom( diameter ); where diameter is a variable of type double you must declare in your main.c
If you had your compiler Warnings turned on, it should have warned you about this.
You should also make the diameter in
double getRadius(float diameter)
double getSurface(float diameter)
and
double getOutline(float diameter)
of type double. In other words, the arguments should be double diameter
Related
Hey guys n gals first time poster first time learning code.
I am sure I am missing something very small that comes naturally when you stare at code long enough. Why are my calculations not working? what am I missing ?
I can get it working without implelemting the # exit but im sure im missing something here.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input;
int a,b,c;
while(1) {
printf("\nPlease Enter Temperature in kelvin \n\nThen enter # when you have had enough:\n ");
scanf(" %c", &input);
if(input == '#'){
break;
}
if(input != '#') {
scanf("%d",&c);
printf("\n1.Convert to celcius\n2.Convert to fahrenheit\nEnter choice now\n");
scanf("%d",&a);
switch(a) {
case 1:
b=(c-273);
printf("Temperature in celcius is %d\n\n",b);
break;
case 2:
b=((c*9)/5)-460;
printf("Temperature in fahrenheit is %d\n\n",b);
break;
default:
printf("You selected wrong choice");
break; /// End of code here
}
}
getchar ();
}
return 0;
}
the following proposed code:
appropriately horizontal spaced
appropriately vertically spaced
includes the suggested changes from the comments to the question
displays how to cleanly display menu
displays how to honor the right margin (column 72 or 80)
replaces 'magic' numbers with meaningful names
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#define CONVERT_KEVIN_TO_CELCIUS 273
#define OFFSET_KEVIN_TO_FAREN 460
int main( void )
{
char input;
int a,b,c;
while(1)
{
printf("%s",
"\nPlease Enter Temperature in kelvin"
"\n\nThen enter # when you have had enough:\n");
scanf(" %c", &input);
if(input == '#')
{
break;
}
ungetc( c, stdin );
scanf("%d",&c);
printf("%s",
"\n1.Convert to celcius"
"\n2.Convert to fahrenheit"
"\nEnter choice now\n");
scanf("%d",&a);
switch(a)
{
case 1:
b=(c-CONVERT_KEVIN_TO_CELCIUS);
printf("Temperature in celcius is %d\n\n",b);
break;
case 2:
b=((c*9)/5)-OFFSET_KEVIN_TO_FAREN;
printf("Temperature in fahrenheit is %d\n\n",b);
break;
default:
printf("You selected wrong choice");
break;
}
}
getchar ();
return 0;
}
Why are my calculations not working?
Code has various technical problem well addressed elsewhere.
Thought I'd mention some numeric issues.
To convert K to °F:
°C = 0K − 273.15
°F = °C×9/5 + 32
To do so with integer math and get the best answer
// (K − 273.15)×9/5 + 32
// (K*100 − 27315)×9/(5*100) + 32
// ((K*100 − 27315)×9 + 32×500)/500
// ((K*100 − 27315)×18 + 32×1000)/1000
// above using real math, below using integer C math
// t = (K*100 − 27315)×18 + 32×1000; (t + signof(t)*500)/1000
// More simplifications possible
int t = (K*100 - 27315) * 18 + 32*1000;
t += (t < 0) ? -500 : 500; // round by adding half the divisor, correctly signed
F = t/1000;
To do so with FP math and get a good integer answer
#include <math.h>
F = lround((K − 273.15)*9.0/5.0 + 32);
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 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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm stuck on this code and have searched the web for an answer and I didn't find anything.
The code get compiled but in options 1 and 2 the code doesn't get the real answer, I don't know if the problem is about the all thing like double and float or because of a stupid mistake.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141
void twoPoints ();
void hypotenuseInTriangular ();
void areaAndScopeInCircle (float radius);
void areaOfSquare ();
void areaOfRectangle ();
int main()
{
int num=0 ;
float radius=0;
double ans1= 0,x1=0,x2=0,y1=0,y2=0;
printf("hello friend, please enter one of the options: \n");
printf("press 1 to calculate length between two points\n");
printf("press 2 to calculate hypotenuse in right tringle \n");
printf("press 3 to calculate area and scope in circle \n");
printf("press 4 to calculate area of square \n");
printf("press 5 to calculate area of rectangle \n");
printf("press 6 to exit from the code \n");
scanf("%d",&num);
switch (num)
{
case 1:
twoPoints(x1,x2,y1,y2);
break;
case 2:
hypotenuseInTriangular();
break;
case 3:
areaAndScopeInCircle (radius);
break;
case 4:
areaOfSquare();
break;
case 5:
areaOfRectangle();
break;
case 6:
printf("bye!\n");
break;
default:
printf("not good number \n");
break;
}
system("PAUSE");
return (0);
}
/**
this funcion calculate the length between two points.
input: two points (x1,y1) (x2,y2).
output: the length between them.
*/
void twoPoints (double x1,double x2,double y1,double y2)
{
double ans1=0,calculate1=0,calculate2=0;
printf("enter two integer points like this: x1 y1 x2 y2\n");
scanf("%1f %1f %1f %1f",&x1,&y1,&x2,&y2);
calculate1 = (x1 - x2) * (x1 - x2);
calculate2 = (y1 - y2) * (y1 - y2);
calculate1 += calculate2;
calculate2 = sqrt(calculate1);
printf("the length between your two points is: %f\n",calculate2);
}
/**
this funcion calculate the hypotenuse in right tringle using two ribs.
input: two integer numbers of the tringle.
output: the hypotenuse length.
*/
void hypotenuseInTriangular (double sideA,double sideB)
{
double sideC=0.0,sum=0.0;
printf("enter two ribs from the triangle: \n");
scanf("%1f %1f",&sideA,&sideB);
sum = (sideA * sideA + sideB * sideB);
sideC = sqrt(sum);
printf("your hyptenuse is %f \n",sideC);
}
/**
this funcion calculate area and scope using radius.
input: a radius number.
output: the area and the scope of this circle.
*/
void areaAndScopeInCircle (float radius)
{
float area = 0,scope =0;
printf("enter radius: \n");
scanf("%f",&radius);
area = PI * radius * radius;
scope = PI * radius * 2;
printf("the area of your circle is: %.1f\n",area);
printf("the scope of your circle is: %.1f\n",scope);
}
/**
this funcion calculate area of square using two ribs.
input: two integer numbers.
output: the area of the square.
*/
void areaOfSquare (int rib)
{
printf("enter one of the square rib: \n");
scanf("%d",&rib);
printf("the area of your square is: %d\n",(rib*rib));
}
/**
this funcion calculate area of rectangle using two ribs.
input: two integer numbers.
output: the area of the rectangle.
*/
void areaOfRectangle (int length,int width)
{
printf("enter length and than width\n");
scanf("%d %d",&length,&width);
printf("the area of your rectangle is: %d\n",(length*width));
}
In your function twoPoints() you have used incorrect format specifiers with
scanf("%1f %1f %1f %1f",&x1,&y1,&x2,&y2);
these could be typos or copying errors because a 1 (numeral one) looks a lot like an l (letter ell). The line should be
scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2);
and after making this correction the function works.
Note that the lower-case L in the format specifier stands for long. In scanf() and friends, for a float variable input you use %f and for a double variable you use %lf. However in printf() and friends, you use %f for double and for float because any float argument is automatically promoted to double.
In your function twoPoints -
scanf("%1f %1f %1f %1f",&x1,&y1,&x2,&y2);
instead of above try this -
scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2); // %lf not %1f
And similar in other funcitons .
Note - Also , your function when defined expect arguments , but when you call them in main , you don't pass them any arguments. Such as this -
hypotenuseInTriangular(); // expects 2 double arguments
Call them with correct arguments , and also declare prototypes correctly .
i'm learning myself programming in c witch basicly no previous programming experience and now i have a weird bug and would like to ask some advice.
In the program flow some of the input data gets suddenly changed and i can't see nor reason why that happens.
1.program starts -> user gets a menu choice -> selects case 1 -> program provides and additional input posiblity.... So far everything works correctly as i could see in debug mode.
2.The user puts in some numbers and the variable gets set to that number.
(this happens in input.c)
3.Then the program continues in main.c to info_bottom().
(in circlemenu.c)
4.In there the function getRadius() gets called that should calculate a radius based on the user input set in input.c in point 2.
5.That calculation function is located in circlefunctions.c
But here/there is the strange thing.
If i look in the debugger, i see that the variable diameter and radius are both changed to some weird numbers and not the number that the user specified in point 2.
Somehow the data stored in the pointer gets corrupted as far as i can judge.
Unfortunately im still to inexperienced with debugging to find this out on my own so hopefully someone can please tell me what is going on.
This problem occured while trying to get rid of all global variables in my program.
Im beginning to get a whole new respect and understanding for professional programmers and why it can take so long sometimes to fix bugs o0.
(i also made the corresponding header files but no need to put them up i think?)
main.c
#include <stdio.h>
#include "menu/menu.h"
#include "circle/circlemenu.h"
#include "input/input.h"
int main(void)
{
while(1)
{
menu();
switch(menu_user_input())
{
case 1:
info_top();
cir_user_input();
info_bottom();
break;
case 2:
system("cls");
break;
case 3:
system("cls");
break;
case 8:
system("cls");
break;
case 9:
system("cls");
break;
case 0:
return(0);
default:
system("cls");
printf("\n **Wrong choice try again...**\n");
break;
}
}
return 0;
}
menu.c
#include <stdio.h>
#include "menu.h"
void menu()
{
printf(" \n Made by ************* 2015.\n");
printf(" ----------------------------------------\n\n");
printf(" 1. Calculate circle measurements. \n");
printf(" 2. \n");
printf(" 3. \n");
printf(" 8. Info. \n");
printf(" 9. Clear screen. \n");
printf(" 0. Exit. \n \n");
printf(" Make your choice and press enter: ");
}
input.c
#include <stdio.h>
#include "input.h"
int menu_user_input()
{
static int number;
scanf(" %i", &number);
return number;
}
float cir_user_input()
{
static float diameter;
scanf("%f", &diameter);
return diameter;
}
circlemenu.c
#include <stdio.h>
#include "circlemenu.h"
#include "circlefunctions.h"
void info_top()
{
system("cls");
printf(" ----------------------------------------\n");
printf(" Typ the diameter of the circle: ");
return;
}
void info_bottom()
{
printf(" ----------------------------------------\n");
printf(" The radius = %f \n\n" , getRadius());
printf(" The surface = %f \n\n" , getSurface());
printf(" The outline = %f \n" , getOutline());
printf(" ----------------------------------------\n");
return;
}
circlefunctions.c
#include "circlefunctions.h"
#include "../input/input.h"
#define PI 3.14
double getRadius()
{
static diameter = (*cir_user_input);
double radius = diameter / 2;
return radius;
}
double getSurface()
{
double radius = getRadius();
return PI * (radius * radius);
}
double getOutline(){
double radius = getRadius();
return 2 * PI * radius;
}
You are using your cir_user_input in your getRadiusfunction like a variable/pointer, although it is a function. It is surprising that this works without any warnings or errors (would be interesting to know what compiler you are using).
I think what you actually intended was something like this, i.e., a call to cir_user_input which stores the result in a float variable.
double getRadius()
{
float diameter = cir_user_input(); //float type; not static (see below)
double radius = diameter / 2;
return radius;
}
Furthermore, the switch statement in your main function only calls the user input function cir_user_input, but none of the calculation routines (case 1). Since the return value of the function is not store, it cannot be used later.
In addition, you have seem to be confused about the use of the static key word:
This problem occured while trying to get rid of all global variables in my program.
When you use the static key word to declare variables inside a function, they retain their values throughout function calls, i.e., they are effectively global.
Conversely, if you use the static key word for a global variable/function etc., it is only visible inside the file you specified it in. For beginners, this is often confusing since the key word is written in exactly the same way, see What does "static" mean?.
Best regards
Andreas
here is a good implementation of the main() function
#include <stdio.h>
#include "menu/menu.h"
#include "circle/circlemenu.h"
#include "input/input.h"
int main(void)
{
int done = 0;
while( !done )
{
menu();
switch(menu_user_input())
{
case 0:
done = 1;
break;
case 1:
info_top();
cir_user_input();
info_bottom();
break;
case 2:
system("cls");
break;
case 3:
system("cls");
break;
case 8:
system("cls");
break;
case 9:
system("cls");
break;
default:
system("cls");
printf("\n **Wrong choice try again...**\n");
break;
} // end switch
} // end while
return 0;
} // end function: main