two similar functions, different results - c

My brain is in pain. I cannot figure what is happening here. I would pay if allowed the person with the best answer.
I have this Weight program for school and it allows user to input starting weight and than through a switch it calls various functions which are either allows user to gain weight or lose weight. Some functions return what I am expecting and some don't. These functions return what I expect cakeGain(), hardWorkout(), mediumWorkout(), but I cant figure out why I am getting incorrect returns on runLoss(), burgerGain(), pizzaGain() and easyWorkout(). I cannot seem to figure out any big difference between the functions and I have tried all kinds of options. I was originally passing my weight variable by reference to all the functions and letting them change the value but my instructor did not want all the pointers.
This is not beautiful code and I have commented out some sections which I will fix later. I know a lot of my work is bad form (system calls etc.) but my instructor has not taught us alternative methods or does not care. This is still considered a beginner course. All I am curious on is why some functions work when others do not.
Thanks again,
Mike (I really appreciate all that take time from their schedules to help people like me out. I cannot wait for the day that I am competent enough to help out others).
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")
#define flush fflush(stdin)
//prototype functions here
void mainMenu(void);
char getUserChoice();
double enterWeight();
double runLoss(double usersWeight);
double burgerGain(double usersWeight);
double eatPizza(double usersWeight);
double eatCake(double usersWeight);
double hardWorkout(double usersWeight);
double mediumWorkout(double usersWeight);
double easyWorkout(double usersWeight);
//void weightChecker(double usersWeight);
int main() {
//declare main variables here
char userChoice = ' ';
double usersWeight;
do {
userChoice = getUserChoice();
switch (userChoice) {
case'A': //get weight
usersWeight = enterWeight();
cls;
printf("Your starting weight is: %dlbs.\n\n",usersWeight);
break;
case'B': //run
usersWeight = runLoss(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'C': //eat burger
usersWeight = burgerGain(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'D': //eat pizza
usersWeight = eatPizza(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'E': //eat cake
usersWeight = eatCake(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'F': //hard workout
usersWeight = hardWorkout(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'G': //medium workout
usersWeight = mediumWorkout(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'H': //easy workout
usersWeight = easyWorkout(usersWeight);
cls;
printf("Your weight is now %d.\n", usersWeight);
//weightChecker(usersWeight);
break;
case'I': //quit
exit(0);
}
} while(userChoice != 'I');
return 0;
} //end of main
char getUserChoice() {
char result;
do {
mainMenu();
scanf("%c", &result);
flush;
result = toupper (result);
} while (result < 'A' || result > 'I');
return result;
}
void mainMenu(void) {
//cls;
printf("A) \tEnter starting weight or change weight\n");
printf("B) \tGo running\n");
printf("C) \tEat Hamburgers\n");
printf("D) \tEat pizza\n");
printf("E) \tEat cake\n");
printf("F) \tDo a hard workout\n");
printf("G) \tDo a medium workout\n");
printf("H) \tDo a easy workout\n");
printf("I) \tQuit\n\n");
printf("Enter your selection: ");
}
double enterWeight() {
double startingWeight = 0.0;
printf("Please enter your starting weight.\n");
scanf("%i", &startingWeight);
flush;
return startingWeight;
}
double runLoss(double usersWeight) {
double result;
double milesRan = 0.0;
double runMinus = 0.0;
printf("How many miles did you run?\n");
scanf("%i", &milesRan);
flush;
runMinus = milesRan * .005;
result = usersWeight - runMinus;
return result;
}
double burgerGain(double usersWeight) {
double result;
double hamburgersAte = 0.0;
double hamburgerGain = 0.0;
printf("How many hamburgers did you eat?\n");
scanf("%i", &hamburgersAte);
flush;
hamburgerGain = hamburgersAte * .005;
if (hamburgersAte > 2) {
hamburgerGain = hamburgerGain + .5;
}
result = usersWeight + hamburgerGain;
return result;
}
double eatPizza(double usersWeight) {
double result;
double pizzas = 0.0;
double pizzaGain = 0.0;
printf("How many pizza's did you eat?\n");
scanf("%i", &pizzas);
flush;
pizzaGain = pizzas * .075;
if (pizzas > 2) {
pizzaGain = pizzaGain + 1;
}
result = usersWeight + pizzaGain;
return result;
}
double eatCake(double usersWeight) {
double result;
double cakesEaten = 0.0;
double cakeGain = 0.0;
printf("How many cakes did you eat?\n");
scanf("%i", &cakesEaten);
flush;
cakeGain = cakesEaten * 2;
result = usersWeight + cakeGain;
return result;
}
double hardWorkout(double usersWeight) {
double result;
double hardWorkoutHours = 0.0;
double hardWorkoutLoss = 0.0;
printf("How many hours did you perform a hard workout?\n");
scanf("%i", &hardWorkoutHours);
flush;
hardWorkoutLoss = hardWorkoutHours * 1;
if (hardWorkoutHours > 2) {
hardWorkoutLoss = hardWorkoutLoss + 1;
}
result = usersWeight - hardWorkoutLoss;
return result;
}
double mediumWorkout(double usersWeight) {
double result;
double mediumWorkoutHours = 0.0;
double mediumWorkoutLoss = 0.0;
printf("How many hours did you perform a medium workout?\n");
scanf("%i", &mediumWorkoutHours);
flush;
mediumWorkoutLoss = mediumWorkoutHours * .5;
if (mediumWorkoutHours > 2) {
mediumWorkoutLoss = mediumWorkoutLoss + .25;
}
result = usersWeight - mediumWorkoutLoss;
return result;
}
double easyWorkout(double usersWeight) {
double result;
double easyWorkoutHours = 0.0;
double easyWorkoutLoss = 0.0;
printf("How many hours did you perform a easy workout?\n");
scanf("%i", &easyWorkoutHours);
flush;
easyWorkoutLoss = easyWorkoutHours * .025;
result = usersWeight - easyWorkoutLoss;
return result;
}
/*void weightChecker(double usersWeight) {
if (usersWeight >= 200 && usersWeight <= 400)
{
printf("You are obese, time to start working out.\n");
}
else if (usersWeight >= 150 && usersWeight < 200)
{
printf("Your weight is considered heavy, time to cut down on junk food.\n");
}
else if (usersWeight >= 125 && usersWeight <150)
{
printf("You are fit, keep up the good work.\n");
}
else if (usersWeight >= 80 && usersWeight <125)
{
printf("You are thin, time to start considering eating more.\n");
}
else
{
printf("You are dead due to improper weight management. Game Over!\n");
pause;
exit(0);
}
pause;
} */

When you print a double or a float value you shoud use %f
float x;
x = eatNutella();
printf("x is %f\n", x);
%d is for decimal values (like int)

Related

this code isnt working the way its supposed to, right after taking shape input its not performing the rest

I have been trying to program a tool, where I take input from the user if its a circle or square or rectangle and accordingly it will take the measurement inputs and print out the area for the same. But its not working, please help me with what are the problems with my code and how can i get it to work?
#include<stdio.h>
#include<math.h>
float square(float side);
float circle(float rad);
float rect(float a,float b);
int main(){
char lol;
printf("press s for square\n c for circle\n r for rectagle\n");
scanf("%c ", &lol);
if(lol == 's')
{
int t;
printf("enter side measurement");
scanf("%d", &t);
printf("the area is %f", square(t));
}
if(lol == 'c');
{
int r;
printf("enter radius of circle");
scanf("%d", &r);
printf("the area is %f", circle(r));
}
if (lol == 'r')
{
int m,n;
printf("enter 2 sides ");
scanf("%d %d", &m,&n);
printf("the area is %f", rect(m,n));
}
return 0;
}
float square(float side){
return side*side;
}
float circle(float rad){
return 3.14* rad*rad;
}
float rect(float a,float b){
return a*b;
}
Screenshot of execution
You want to remove the trialing ' ' in the first scanf(), and remove the ; after the if statement.
If main() is last you often can get away with not specifying prototypes for small programs like this. Added error checking of scanf(). Prefer if-else-if when the conditions are mutually exclusive, or as here a switch statement so you don't need to repeat the lol == . Prettied up the prompts a bit (colons, newlines), and sorted both the menu and matching implementation. It makes it easier for end-users and easier to navigate for anyone working on the code. math.h defined the constant M_PI if __USE_XOPEN is set. It's better to use a constant than hard-coding the 3.14 value in circle().
#define __USE_XOPEN
#include <math.h>
#include <stdio.h>
float circle(float rad) {
return M_PI * rad * rad;
}
float rect(float a, float b) {
return a * b;
}
float square(float side) {
return side * side;
}
int main(void) {
printf("press:\n"
" c for circle\n"
" r for rectangle\n"
" s for square\n"
);
char lol;
if(scanf("%c", &lol) != 1) {
printf("scanf failed\n");
return 1;
}
switch(lol) {
case 'c': {
printf("enter radius of circle: ");
int r;
if(scanf("%d", &r) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", circle(r));
break;
}
case 'r': {
printf("enter 2 sides: ");
int m, n;
if(scanf("%d %d", &m,&n) != 2) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", rect(m,n));
break;
}
case 's': {
printf("enter side measurement: ");
int t;
if(scanf("%d", &t) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", square(t));
break;
}
default:
printf("invalid selection %c\n", lol);
}
}

Passing value from one function to another function in C

I'm attempting to pass a value determined by one function to another function that comes after it. Essentially: Function 1 determines a value, lets say x. Then X is passed to another function that specifically displays X as text. It's in a separate function to be used by other functions who can also determine the value of X. However, i'm only getting 0 instead of the variable x. What is wrong here?
float fahToCel(int userInput)
{
float result = 0;
do
{
printf("\nPlease input your number in Fahrenheit units:");
scanf("%d", &userInput);
} while (result = 0);
result = (float)(((float)5.0f / (float)9.0f) * (float)(userInput - 32));
return result;
}
float celToFah(int userInput){
float result = 0;
do
{
printf("\nPlease input your number in Celcius units:");
scanf("%d", &userInput);
} while (result = 0);
result = (float)(((float)9.0f / (float)5.0f) * (float)(userInput + 32));
return result;
}
float displayResult(float result) {
printf("\nThe equivalent tempature is: %f\n", result);
return result;
}
void inputInformation() {
printf("1. Convert temperature input from the user in degrees Fahrenheit to
degrees Celsius.\n");
printf("2. Convert temperature input from the user in degrees Celsius to
degrees Fahrenheit.\n");
printf("3. Quit.\n ");
}
int main()
{
int menuChoice = 0;
int userInput = 0;
int result = 0;
while (1)
{
inputInformation();
printf("Please make a selection now:");
scanf("%d", &menuChoice);
switch (menuChoice)
{
case 1:
fahToCel(userInput);
displayResult(result);
break;
case 2:
celToFah(userInput);
displayResult(result);
break;
case 3:
return 0;
default:
printf("\nThat is not a choice!\n");
break;
}
}
}
You never assign the result to result. Change like this:
result = fahToCel(userInput);
displayResult(result);

Could someone please why this program is not running correctly. I'm new to C

Good evening. I just started learning C in college and our 1st assignment was to make a program that calculates the user's bmi. For the life of me I can't figure out why Im not getting the results I want. No matter what height & weight I submit to the program...I keep getting a ridiculously high bmi like 4258544 and then it tells me I'm underweight. i thought I could use another set of eyes.
Please help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void h_conversion (double *h) {
*h = *h/12;
}
int bmi_category (double h, double w, double b) {
b = (w * 4.88)/(h * h);
if (b < 20)
return 1;
else if (b >= 20 && b < 25)
return 2;
else if (b >= 25 && b < 30)
return 3;
else if (b >= 30 && b < 40)
return 4;
else
return 5;
}
int main (void) {
double height, weight, bmi;
double *h, *w, *b;
h = &height;
w = &weight;
b = &bmi;
printf ("Please enter height (inches): \n");
scanf (" %lf", &height);
while ( h <= 0 ) {
printf ("Weee, this is fun! Try again.\n");
scanf (" %.2lf", &height);
}
if ( *h < 42 || *h > 84 )
printf ("Your entry falls outside the norm for an adult.\n");
h_conversion( h );
printf ("Please enter weight (lbs): \n");
scanf (" %.2lf", &weight);
while ( w <= 0 ) {
printf ("This is why we can't have nice things. Try again.\n");
scanf (" %.2lf", &weight);
}
switch ( bmi_category(*h, *w, *b)) {
case 1:
printf ("BMI: %d. Underweight.", (int)&bmi);
break;
case 2:
printf ("BMI: %d. Normal weight.", (int)&bmi);
break;
case 3:
printf ("BMI: %d. Slightly overweight.", (int)&bmi);
break;
case 4:
printf ("BMI: %d. Overweight.", (int)&bmi);
break;
case 5:
printf ("BMI: %d. Extremely overweight.", (int)&bmi);
break;
default:
printf ("error condition\n");
}
system ("pause");
return 1;
}
In your printf's you're using
(int)&bmi
// this request the address of bmi and casts that value to an integer (addresses are always integers)
When you should be using
(int)bmi
// this casts the value of the variable bmi to an integer which is what you want.
The weird values you're always getting is because you're getting addresses instead of the values of the variables.
Also why all the pointer variables? You only need the h one. The bmi function doesn't require you use pointers so why use them instead of the of its non-pointer counterparts?
Also main returns 0 when it's finished its execution without any issues. For some reason you're returning 1 indicating the program didn't finish execution properly.
int bmi_category (double h, double w, double b) {
b = (w * 4.88)/(h * h);
...
switch ( bmi_category(*h, *w, *b)) {
case 1:
printf ("BMI: %d. Underweight.", (int)&bmi);
The assignment to b inside bmi_category will not change the value
of bmi in your main routine, as you seem to expect, since you're passing
the value *b, rather than the pointer b. And as another answer points out, the (int)&bmi expressions are also not what you need.
for double should use it:
scanf("%lf", &height);
In your call to bmi_category function, the parameters were passed incorrectly. You were passing the value when pointer was expected. Because of this, the value of calculated bmi was local to the bmi_category function and wouldn't get updated to the caller.
When printing the value of bmi, you were printing the address &bmi instead of the value.
Here is the fixed code with a little cleanup:
#include <stdio.h>
#include <stdlib.h>
void h_conversion(double *h) {
*h = *h / 12;
}
int bmi_category(const double *h, const double *w, double *b) {
*b = (*w * 4.88) / (*h * *h);
if (*b < 20)
return 1;
else if (*b >= 20 && *b < 25)
return 2;
else if (*b >= 25 && *b < 30)
return 3;
else if (*b >= 30 && *b < 40)
return 4;
else
return 5;
}
int main(void) {
double height, weight, bmi;
printf("Please enter height (inches): \n");
scanf(" %lf", &height);
while (height <= 0) {
printf("Weee, this is fun! Try again.\n");
scanf(" %lf", &height);
}
if (height < 42 || height > 84)
printf("Your entry falls outside the norm for an adult.\n");
h_conversion(&height);
printf("Please enter weight (lbs): \n");
scanf(" %lf", &weight);
while (weight <= 0) {
printf("This is why we can't have nice things. Try again.\n");
scanf(" %lf", &weight);
}
switch (bmi_category(&height, &weight, &bmi)) {
case 1:
printf("BMI: %d. Underweight.", (int)bmi);
break;
case 2:
printf("BMI: %d. Normal weight.", (int)bmi);
break;
case 3:
printf("BMI: %d. Slightly overweight.", (int)bmi);
break;
case 4:
printf("BMI: %d. Overweight.", (int)bmi);
break;
case 5:
printf("BMI: %d. Extremely overweight.", (int)bmi);
break;
default:
printf("error condition\n");
}
system("pause");
return 1;
}

Microsoft Visual Studio 2013 C Program Exception

I am using Microsoft Visual Stusio 2013 Community Edition Update 4 to write a program in the C programming language (not C++). Whenever I try to build and run my program, partway through execution it tells me "Unhandled exception at 0x52873FD4 (msvcr120d.dll) in program.exe: 0xC0000005: Access violation writing location 0x00C40000." When I copy and paste the contents of the .c file into another IDE (code blocks) it compiles and runs without a problem. (Although I do have to change all the scanf_s statements in the code to scanf)
The source code from within the .c file of my program
#include <math.h>
#include <stdio.h>
#include <string.h>
#define PI 3.14159265358979323846;
double add();
double cos_d_r();
double div();
double mult();
void list();
int main()
{
//Declaration of variables
char oper[20];
double ans;
int loop = NULL;
//While loop allows for multiple executions without restarting program
while (!loop)
{
printf("\n\nEnter a mathematical operation.\n\nFor a list of options, enter 'list'\n\n");
scanf_s(" %s", oper);
//If statement to determine which operation to do
//Addition
if (strcmp(oper, "add") == 0 || strcmp(oper, "addition") == 0 || oper[0] == '+')
{
ans = add();
printf("The sum is %.2f\n", ans);
}
//Cosine
else if (strcmp(oper, "cos") == 0 || strcmp(oper, "cosine") == 0)
{
ans = cos_d_r();
printf("The cosine of the angle is %lf\n", ans);
}
//Division
else if (strcmp(oper, "divide") == 0 || strcmp(oper, "division") == 0 || oper[0] == '/')
{
ans = div();
printf("The quotient is %.2f\n", ans);
}
//List of possible operations
else if (strcmp(oper, "list") == 0)
{
list();
}
//Multiplication
else if (strcmp(oper, "multiply") == 0 || strcmp(oper, "multiplication" == 0) || oper[0] == '*')
{
ans = mult();
printf("The product is %.2f", ans);
}
}
return 0;
}
//Declaration of functions
//Addition
double add()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 + num_2;
return ans;
}
//Cosine
/*Uses cos() function from math.h
this function adds option for degrees or radians*/
double cos_d_r()
{
char deg_rad;
double angle;
double ans;
int loop = NULL;
while (!loop)
{
puts("Degrees or radians? Enter 'd' or 'r'");
scanf_s(" %c", &deg_rad);
//Degrees
if (deg_rad == 'd')
{
puts("Enter an angle in degrees");
scanf_s(" %lf", &angle);
angle = angle / 180 * PI;
ans = cos(angle);
loop = 1;
return ans;
}
//Radians
else if (deg_rad == 'r')
{
puts("Enter an angle in radians");
scanf_s(" %lf", &angle);
ans = cos(angle);
loop = 1;
return ans;
}
//Else statement repeats loop if user enters text other than 'd' or 'r'
else
{
puts("ERROR. Enter either 'd' or 'r'");
}
}
}
//Division
double div()
{
double ans;
double num_1;
double num_2;
puts("Enter the dividend");
scanf_s(" %lf", &num_1);
puts("Enter the divisor");
scanf_s(" %lf", &num_2);
ans = num_1 / num_2;
return ans;
}
//Multiplication
double mult()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 * num_2;
return ans;
}
//List of possible operations
void list()
{
printf("The possible operations are:\n\n");
printf("Operation\tDescription\tCommand");
printf("Addition\tAdds two numbers together\tAdd, Addition, +\n");
printf("Cosine\tFinds the cosine of the angle entered\tCos, Cosine");
printf("Division\tDivides the first number by the second\tDivide, Division, /");
printf("Multiplication\tMultiplies the two numbers\tMultiply, Multiplication, *");
}
You should read description of functions you use first! Take a look at scanf_s function description at MSDN. You programm crashes at first call of this function
scanf_s(" %s", oper);
The correct way to use it:
scanf_s("%s", oper, _countof(oper)); // or sizeof(oper), but only with char array
Also you should correct other calls of scanf_s in your code. (Or disable errors for scanf call with #define _CRT_SECURE_NO_WARNINGS before #include <stdio.h>)

calculation of wall clock

How to modify this code to do sequential
program to calculate the wall clock time
(time_t) needed to calculate the dot product
of the complex numbers.
#include "stdafx.h"
#include <stdlib.h>
#include<stdio.h>
typedef struct complex{
double real;
double img;
}complex;
complex add(complex a, complex b);
complex multiply(complex *a, complex *b);
int _tmain(int argc, _TCHAR* argv[])
{
int choice, temp1, temp2;
complex a, b, c;
while (1)
{
printf("Press 1 to add two complex numbers.\n");
printf("Press 2 to multiply two complex numbers.\n");
printf("Press 3 to exit.\n");
printf("Enter your choice\n");
scanf_s("%d", &choice);
if (choice == 3)
exit(0);
if (choice >= 1 && choice <= 2)
{
printf("Enter a and b where a + ib is the first complex number.");
printf("\na = ");
scanf_s("%d", &a.real);
printf("b = ");
scanf_s("%d", &a.img);
printf("Enter c and d where c + id is the second complex number.");
printf("\nc = ");
scanf_s("%d", &b.real);
printf("d = ");
scanf_s("%d", &b.img);
}
if (choice == 1)
{
c.real = a.real + b.real;
c.img = a.img + b.img;
if (c.img >= 0)
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di", c.real, c.img);
}
else if (choice == 2)
{
c.real = a.real*b.real - a.img*b.img;
c.img = a.img*b.real + a.real*b.img;
if (c.img >= 0)
printf("Multiplication of two complex numbers = %d + %di", c.real, c.img);
else
printf("Multiplication of two complex numbers = %d %di", c.real, c.img);
}
else
printf("Invalid choice.");
printf("\nPress any key to enter choice again...\n");
}
}
A typical approach is to record time() twice and run the code many times to get a 1st order approximation.
time_t t0,t1;
time(&t0);
int N = 1000000;
for (int i=0; i< N; i++) {
DoCodeUnderTest();
// c.real = a.real + b.real;
// c.img = a.img + b.img;
}
time(&t1);
printf("Time %e\n", (double) (t1-t0) / N);
Suggest using profiling tools for a more accurate answer.
#Jonathan Leffler suggestion to use clock() is also an improvement.
clock_t c1,c12;
c1 = clock();
... // repeat runs of the code
c2 = clock();
printf("Time %e\n", (double) (c1-c0) / CLOCKS_PER_SEC / N);
Given 1) #Jonathan Leffler 2nd suggestion about the legitimacy of repeating since a compiler may out-think the code and 2) cache issues hints that any brute force methods as suggested here are at best illustrative and not definitive time measurements.

Resources