How to debug a C program producing unexpected output? - c

I am new to programming C and I don't know why my program is not printing the desired output.
#include <stdio.h>
void main(void)
{
char res,res1;
float money=10;
printf("***Wealcome to Peace of Mind***");
printf("\nHello we have the menu please check::");
printf("\n***Menú***");
printf("\n");
printf("\n<<<Bebidas>>>");
printf("\n 1 - Coca-Cola = 1,5 2 - IceTea = 1,4");
printf("\n 3 - Super Bock = 1,70 4 - Sumol = 1,6");
printf("\n");
scanf("%d",&res);
switch(res)
{
case 1 || 'Coca-Cola':money - CocaCola;break;
}
printf("%.1f",money);
//Is that result i want:
printf("\n%.1f",10-1.5);
}
Output of my program:

The syntax of your case statement is not correct. Also the code is using scanf() to read an integer, but storing the integer-sized value in a char.
I tidied up the code:
#include <stdio.h>
int main(void)
{
int res;
float cost = 0;
float money = 10;
printf("***Wealcome to Peace of Mind***\n");
printf("Hello we have the menu please check::\n");
printf("***Menú***\n");
printf("\n");
printf("<<<Bebidas>>>\n");
printf(" 1 - Coca-Cola = 1,5 2 - IceTea = 1,4\n");
printf(" 3 - Super Bock = 1,70 4 - Sumol = 1,6\n");
printf("\n");
scanf("%d", &res);
switch(res)
{
case 1:
cost = 1.5;
break;
case 2:
cost = 1.4;
break;
// TODO: case 3 & 4
default:
printf("Invalid Entry\n");
cost = 0;
}
printf("money = %.1f\n", money - cost);
return 0;
}
Some further notes:
As commentators pointed out, put \n at the end of the string
When you compile, turn on warnings, and try to fix all of them.
In case blocks, it's good practice to have a default to catch errors
It would be worthwhile to store the drink prices as #define constants (or as an array of values, or some common area so the value is only set once in the program, and everything else just references that.)
#define COLA_COST 1.5

Related

C code Calculations not outputting correctly after adding exit for program

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);

How do I get the proper output for the color bands of a 3 band resistor?

I am taking a programming class as an elective. Our current lab is to create a program that accepts a number from the user that represents a resistor band. The max would be two digits followed by 9 zeros; 11 total digits. After accepting the number I have a few functions that find the first two digits, then the modulus for the second band and divide by 10 for the first. My issue lies in using a logarithm 10 function and even trying a loop with a counter to find the number of zeros. I have gotten it to be able to count 8 zeros, but once the ninth gets added it messes everything up including the first number. In my code I have some instruction or information and some functions stagnant as I hid them to try different options. I currently have just been trying to be able to enter 99000000000 and get "White" in return for all three numbers. Any ideas where I am going wrong?
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
long int inputValue();
void outputColor(int);
int bandCalc(long int);
int loop(long int);
int divideResistor(int);
// function prototypes // '''
int main()
{
int resistor, x, y, z, a, b, c, f;
resistor = inputValue();
//printf("\n\tThe resistor value is %d", resistor);//
c = resistor;
b = divideResistor(resistor);
f = loop(b);
//printf("\t\nThe number is %d", b);//
if (f <= 10)
{
f = log10(c) - 1;
}
else
{
f = log10(c) - 2;
}
//Here we are finding out how many zeros there are in the number//
printf("\n\tThe character x equals %d", x);
y = bandCalc(b); //Here we are getting the first two digits of the resistor value//
printf("\n\tThe character y equals %d", y);
z = fmod(y, 10); //Here we are finding the second digit of the resistor//
printf("\n\tThe character z equals %d", z);
a = (y / 10); //Here we are finding the first digit of the resistor//
printf("\n\tThe character a equals %d", a);
x = bandCalc(resistor);
printf("\n\tThe returned number is %d", x);
printf("\n\n\tThe color of the resistor bands are: \n\n");
printf("\n\t");
outputColor(a);
printf("\t ");
outputColor(z);
printf("\t ");
outputColor(f);
system("pause>nul");
return 0;
}
int divideResistor(int s)
{
s = s / 10;
return (s);
}
int loop(long int j)
{
int k;
k = 0;
if (j >= 100)
}
}
j /= 10;
k++;
for (j > 100; j /= 10; k++)
k <= 9;
printf("%d ", k);
return (k);
}
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band);
return (band);
}
int bandCalc(long int z)
{
long n = z;
long n1 = n, n2 = n;
while (n)
{
n2 = n1;
n1 = n;
n /= 10;
}
return (n2);
}
void outputColor(int i)
{
switch (i)
{
case 0:
printf(" Black");
break;
case 1:
printf(" Brown");
break;
case 2:
printf(" Red");
break;
case 3:
printf(" Orange");
break;
case 4:
printf(" Yellow");
break;
case 5:
printf(" Green");
break;
case 6:
printf(" Blue");
break;
case 7:
printf(" Violet");
break;
case 8:
printf(" Grey");
break;
case 9:
printf(" White");
break;
//return (band);//
}
}
Take a look at your inputValue function:
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band); // format-specifier for a "long int" is "%ld"
return (band);
}
You are using a long to store the input, but you are telling scanf that band is only an int, so it will only be able to store values as high as INT_MAX (2147483647 for 32-bit two's complement ints). Assuming long is a 64-bit type on your system, it will be able to handle much larger values (9223372036854775807).
Try fixing your scanf call there to use the %ld format-specifier: scanf("%ld", &band);
Similarly, look at the type of resistor which takes the return of inputValue. It is of type int, so it won't be able to handle values that are outside of that INT_MAX range. That should also be type long. You'll also need to modify the input of functions such as divideResistor to take a long.
Beyond the issues of not using large enough integer types, you are also using floating-point operations on integer-type data. which can create rounding errors. log10, for example, is meant to handle double types. fmod is also intended for double types (the % operator is used do perform 'modulo' operations on integer types)
There may be further errors beyond these. If you find yourself having more trouble, please give this link a look-over and see if it helps you to help yourself, or at least help you construct a Minimal Complete Verifiable Example of specific issues rather than a scavenger hunt to find all the errors in your full program.

Trying to get a variable equal to other variables in C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int score=0;
int loop=0;
int randNUM1=0;
char randSYMB1=0;
int randNUM2=0;
int correct_answer=0;
int answer=0;
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10; printf("%c", "0123456789"[randNUM1]);
randSYMB1 = rand()%4; printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10; printf("%c\n", "0123456789"[randNUM2]);
printf("What is your answer?");
scanf("%d", &answer);
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
if (randSYMB1=="/")
{
printf("The correct answer is %d\n", randNUM1/randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="*")
{
printf("The correct answer is %d\n", randNUM1*randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="+")
{
printf("The correct answer is %d\n", randNUM1+randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="-")
{
printf("The correct answer is %d\n", randNUM1-randNUM2);
scanf("%d", &correct_answer);
score++;
}
printf("Your score is %d\n", score);
}
}
The code is for a simple calculation game, in which the user is asked 10 questions, which consist of randomly generating a number, then a symbol then another number, the answer is then stored, and then the user is told whether their answer was correct, and at the end of the 10 questions the user is given a score out of 10. My code seems to generate the numbers and the symbols randomly, and loops for 10 questions, but however, the code does not seem to take the IF statements into account, which then means that the correct answer isn't displayed, and thereofre, the score output to the user after every question is 0. Therefore, from what I can teel there is a problem with the IF statements, but I can't understand, what that problem is. I have also tried to use CASE statements instead, but the problem is still the same; the statements are not taken into account by the program. I cannot understand why the program does this. Is it a problem in the FOR loop, or is the probelm with the problem with the "correct_answer" variable? Please help!
Benny, much of the difficulty you are having just stems from apparently just starting in coding. There is nothing wrong with that, if you knew it all already, then you wouldn't need to learn... (and you are never really done learning how to program, hardware changes, standards change, etc.. It's a journey not a race)
First, if you have the option, declare all variables before you begin executing statements. This will keep your code portable to compilers still using the C89 standard (all windoze versions through Win7), e.g.
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL)); /* now begin executing statements */
It's a matter of style, but if you open the spacing up a bit, it will make your code more readable (especially for older eyes...). While you can save lines by cramming two expressions on each line or using the comma operator -- don't. It just makes your code harder to read (for you and anyone else). Sure, if it is stupid-short, then you can get away with it, e.g.
if (!a) b = 1;
otherwise, put each statement on it's own line:
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
Next, the crux of your issues are how to handle the logic of checking the math operation and the user's answer. All of the logic is based on what random character was generated with randSYMB1 = symbol[rand() % 4]; (my changes).
How do you take different actions based on a what one of a set of characters could be? Well, you can daisy-chain a whole string of if and else if statements together, or, just use a switch statement:
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
That leaves your a single simple comparison to determine if the correct answer was entered:
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
(note: for division, the user must enter the result of what integer division would produce)
Putting it altogether, you could boil your code down to:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void) {
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL));
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
}
return 0;
}
Example Use/Output
C:\Users\david\Documents\dev\src-c\tmp>bin\mathtest.exe
9 + 3
What is your answer?: 12
Correct!
Your current score is: 1
8 * 8
What is your answer?: 64
Correct!
Your current score is: 2
5 + 7
What is your answer?: 12
Correct!
Your current score is: 3
6 - 4
What is your answer?: 2
Correct!
Your current score is: 4
6 / 4
What is your answer?: 1
Correct!
Your current score is: 5
7 * 9
What is your answer?: 63
Correct!
Your current score is: 6
5 / 6
What is your answer?: 0
Correct!
Your current score is: 7
8 * 2
What is your answer?: 16
Correct!
Your current score is: 8
0 / 1
What is your answer?: 0
Correct!
Your current score is: 9
9 + 7
What is your answer?: 16
Correct!
Your current score is: 10
Look things over and let me know if you have further questions.
There are several problems with your code. randSYMB1 will have a value of 0 to 3, none of which corresponds to the ascii values of /*+-.
Change the if statements to:
if (randSYMB1==0)
and accordingly to the rest. Also, you should never write something like:
char c;
...
if(c == "x")
You should use single quotes:
if(c == 'x')
This line:
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
is complete jibberish. Move the calculation of correct value inside the if statements.
This:
printf("%c", "0123456789"[randNUM1]);
works, but it's pretty insane. This is better:
printf("%d", randNUM1);
I guess it's ok as a quick workaround for randSYMB1 but there's no reason at all with the operands.
Here is a working version of the for loop:
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10;
printf("%d", randNUM1);
randSYMB1 = rand()%4;
printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10;
printf("%d\n", randNUM2);
printf("What is your answer?");
scanf("%d", &answer);
if (randSYMB1==0)
correct_answer=randNUM1/randNUM2;
else if (randSYMB1==1)
correct_answer=randNUM1*randNUM2;
else if (randSYMB1==2)
correct_answer=randNUM1+randNUM2;
else if (randSYMB1==3)
correct_answer=randNUM1-randNUM2;
printf("The correct answer is %d\n", correct_answer);
if(answer == correct_answer)
score++;
printf("Your score is %d\n", score);
}
If never executes because randSYMB1 is number between 0-3, and not "/*-+". Also i suggest seeding random first, but in this case it doesn't matter.

C program dice game

I am in trouble with my dice game. I have a task:
The rules of the game are the following:
1. The player rolls the dice and adds up the face values.
2. If the first roll is a 7 or 11, the player wins.
3. If the first roll is a 2, 3 or 12, the player looses.
4. If the first roll is any other number, that sum becomes the player's point.
5. To win, the player must continue rolling the dice until he/she “makes point.”
6. The player loses by rolling a 7 before the point.
1) Define WON and LOST as macros in your program. Use the values of 0 for WON and 1 for LOSE
2) Implement a function, with function prototype int rollDice( void );
rollDice( ) should use rand( ) to randomly generate a number between 1 - 6
return the number generated by rand( )
3) Implement a function, with function prototype int playGame( void ); 
When the player is ready to play, (s)he would use the key ENTER to roll the dice
If the user wins in his/her first roll, congratulate the player and return with WON
If the user looses in his/her first roll, congratulate the player and return with LOSE
Let the user keep playing until (s)he wins / loses, give an appropriate massage and finish the game with the last roll value.
4) Your main( ) should
Call your function playGame( )
Ask the user if (s)he wants to continue playing another game, keeping track of the numbers of losses and wins
When the user decides to finish playing, display the number of wins and losses (s)he had.
Give the user an appropriate message depending on the number of wins or losses (s)he had
Return with a value of EXIT_SUCCESS
Here is what I have now, but it tells me that there are mistakes. Can anyone please help me with this task?
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#define WON 0
#define LOSE 1
int rollDice(void);
int playGame(void);
int rollDice(void) {
return ((rand() % 6) + 1);
}
int playGame(void){
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
time_t t;
srand(time(&t));
printf("ROLL THE DICE WITH [ENTER]\n");
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
if (sum == 7 || sum == 11){
printf("Congratulations you roll %d and WON at your first try!", sum);
}
else {
printf("Your roll was %d ,you lose try agian.\n", sum);
}
return 0;
}
int main (void){
playGame();
}
The Error is (in gcc linux):
x.c:9:1: error: stray ‘\302’ in program
int rollDice(void);
^
x.c:9:1: error: stray ‘\240’ in program
x.c:10:1: error: stray ‘\302’ in program
int playGame(void);
^
x.c:10:1: error: stray ‘\240’ in program
x.c:12:1: error: stray ‘\302’ in program
int rollDice(void) {
^
x.c:12:1: error: stray ‘\240’ in program
x.c:16:1: error: stray ‘\302’ in program
int playGame(void){
^
x.c:16:1: error: stray ‘\240’ in program
There are a few things wrong here.
You're not reading/using the return value from playGame(). You should be storing the result and acting on it.
Your logic isn't complete, as the criteria for "playing for point" and a loss both are the same.
You don't have anything in place that forces the program to wait for the user to press ENTER.
I have included a completed code listing for you below.
Code Listing
/*******************************************************************************
* Preprocessor directives
******************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define WON 0
#define LOSE 1
/*******************************************************************************
* Function prototypes
******************************************************************************/
int rollDice(void);
int playGame(void);
/*******************************************************************************
* Function definitions
******************************************************************************/
/*----------------------------------------------------------------------------*/
int rollDice(void) {
return ((rand() % 6) + 1);
}
/*----------------------------------------------------------------------------*/
int playGame(void){
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
int result;
int point = 0;
time_t t;
bool playForPoint = false;
srand(time(&t)); // Initialize random seed
printf("ROLL THE DICE WITH [ENTER]\n");
fgetc(stdin);
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("D1:%2d - D2:%2d - Sum:%2d\n", dice_1, dice_2, sum);
switch ( sum )
{
case 7:
case 11:
result = WON;
break;
case 2:
case 3:
case 12:
result = LOSE;
break;
default:
playForPoint = true;
point = sum;
printf("Playing for point:%d. Please hit enter.\n", point);
fgetc(stdin);
break;
}
while ( playForPoint )
{
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("D1:%2d - D2:%2d - Sum:%2d\n", dice_1, dice_2, sum);
if ( sum == 7 ) {
playForPoint = false;
result = LOSE;
} else if ( sum == point ) {
playForPoint = false;
result = WON;
} else {
printf("Please roll the dice again with [ENTER].\n");
fgetc(stdin);
}
}
return result;
}
/*----------------------------------------------------------------------------*/
int main (void){
int result = playGame();
switch ( result )
{
case WON:
printf("You won the game.\n");
break;
case LOSE:
printf("You lost the game.\n");
break;
default:
printf("Something went wrong in the program.\n");
break;
}
return 0;
}
Sample Output
ROLL THE DICE WITH [ENTER]
D1: 3 - D2: 5 - Sum: 8
Playing for point:8. Please hit enter.
D1: 3 - D2: 1 - Sum: 4
Please roll the dice again with [ENTER].
D1: 3 - D2: 2 - Sum: 5
Please roll the dice again with [ENTER].
D1: 1 - D2: 5 - Sum: 6
Please roll the dice again with [ENTER].
D1: 3 - D2: 2 - Sum: 5
Please roll the dice again with [ENTER].
D1: 2 - D2: 6 - Sum: 8
You won the game.
You haven't yet satisfied the rules of the game. Your code takes 7 and 11 as winners and any other number as a loser.
After the 7/11 check, you need to check for 2, 3, or 12 and print a "lose" message if true. If not, you have the point number, and you need to prompt the user to keep rolling until he either gets the point number (win) or a 7 (lose).
You also need to keep track of wins/losses in main. You'll need to call playGame in a loop, prompting the user to continue on each iteration.

Stored data gets corrupted in C

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

Resources