Question:
what's wrong with the code ?
Ahmed
2013-04-08 15:05:48 UTC
I'm learning C and using Pelles C .... I was writing a program to do math on imaginary numbers but the execution goes until "op = getchar()" and stops ... what's wrong with it?

#include
#include

int main()
{
char op;
float a,b,c,d,Vr,Vi;

printf("\nNUM.1 = a+bi\n\nNUM.2 = c+di\n\na = ");
scanf("%f",&a);
printf("\nb = ");
scanf("%f",&b);
printf("\nc = ");
scanf("%f",&c);
printf("\nd = ");
scanf("%f",&d);

printf("\n\nPlease enter the symbol of the operation >");
op = getchar();

switch(op)
{
case '+': printf("\n\nSummation = %f + %fi",a+c,b+d);
break;

case '-': printf("\n\nSubtraction = %f + %fi",a-c,b-d);
break;

case '*':
{
Vr = a*c + b*d;
Vi = b*c + a*d;
printf("\n\nMultiplication = %f + %fi",Vr,Vi);
}
break;

case '/':
{
Vr = (a*c - b*d)/(c*c + d*d);
Vi = (c*b - a*d)/(c*c + d*d);
printf("\n\nDivision = %f + %fi",Vr,Vi);
}
break;


};
}
Three answers:
Jacob
2013-04-08 15:10:15 UTC
there could be a problem with getchar() I believe you are looking for _getch() IE.



op = _getch();
2013-04-08 18:41:19 UTC
scanf is leaving trailing newlines in your input which is causing the call to getchar() to be skipped.



To fix it add the following code before your getchar()

while(getchar() != '\n);



Here is the corrected code which behaves as expected:

http://pastebin.com/AdSd5LPC
2014-07-13 01:35:29 UTC
extremely tough situation search into bing and yahoo that will may help


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...