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!

Kara
  • 6,115
  • 16
  • 50
  • 57
lulaz
  • 35
  • 2
  • 6

2 Answers2

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++?.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Whaaaaa thank you so much.... I knew it would be something beyond stupid like that, just needed a fresh pair of eyes! Thanks again. – lulaz Oct 19 '13 at 11:50
  • @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 – Grijesh Chauhan Oct 19 '13 at 12:22
0

Use

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

in place of

scanf("%c", calctype);
adesh
  • 160
  • 4