1

I wrote this really simple code to find resistor values. the code will compile and asks the initial question but when an input of P or S is inputted the code crashes and exits. Any help would be great, I know it will be something really simple I'm missing out...

#include <stdio.h>

void main ()
{
float res1;
float res2;
float res3;
float answer;
char calctype;

printf("Please enter 1st resistor value:");
   scanf("%f", &res1);

printf("Enter 2nd resistor value:");
   scanf("%f", &res2);

printf("Enter 3rd resistor value:");
   scanf("%f", &res3);

puts("type P for Parallel calculation or S for Series calculation:\n");
scanf("%c", calctype);

if (calctype == 'S') {
answer = res1 + res2 + res3;
printf("The Series value is:%f \n", answer);
}
else if (calctype == 'P') {
answer = 1/(1/res1 + 1/res2 + 1/res3);
printf("The Parallel Value is:%f \n", answer);
}

}

Thank you!

2 Answers 2

5

The scanf() function call is wrong, forgot &:

scanf("%c", calctype);
// calctype is declared as char variable you need address of it  

should be:

scanf("%c", &calctype);
 //         ^ added & - pass by address to reflect change  

One side note:
Use switch-case instead of if-else-if.

switch(calctype){
 case 'S' :  /* First if code 
             */
            break;
 case 'P':  /*  Second if code
            */
            break;
}

In general it is good coding practice to use flat coding structure is preferable then nested if-else.

You also need to improve indentation in your code, Read Indenting C Programs. which will also tell you about some good coding practice.

Also note don't use void main(), according to the C standard main is to be defined as int main(void), as int main(int argc, char *argv[]). Read What should main() return in C and C++?.

Sign up to request clarification or add additional context in comments.

2 Comments

Whaaaaa thank you so much.... I knew it would be something beyond stupid like that, just needed a fresh pair of eyes! Thanks again.
@LauraStokes read updated answer, added a link in answer regarding indentation and good coding practice, it will take just 2-3 hours to read it I highly encourage you to read it
0

Use

scanf("%c", &calctype); /* put ampersand before variable name */

in place of

scanf("%c", calctype);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.