2015-03-17 2 views
-1

Я написал этот код, чтобы сделать некоторую алгебру с мнимыми числами с помощью структур, но когда я запускаю его, я получаю это enter image description hereЧто случилось с getchar в C, пожалуйста?

Что я делаю неправильно я пытался все различные способы, чтобы получить символ, я озадачен !!

#include<stdio.h> 
#include<stdlib.h> 
#include <string.h> 

struct complex { float Rez, Imz; }; 

int main() 
{ 
    char operand; 
struct complex z1, z2; 
printf("give the Real part of the first imaginary number z1:\n"); 
scanf("%f", &z1.Rez); 
printf("zreal=%f",z1.Rez); 
printf("give the Imaginary part of the first imaginary number z1: \n"); 
scanf("%f", &z1.Imz);  
printf("give the Real part of the second imaginary number z2: \n"); 
scanf("%f", &z2.Rez); 
printf("give the Imaginary part of the second imaginary number z2: \n"); 
scanf("%f", &z2.Imz); 
do 
{ 
    printf("Give + for ADD\nGive * for MULTIPLICATION\nGive - for SUBTRACTION\nGive/for DIVISION\n"); 
    operand=getchar(); 
    if (operand!='+' || operand!='-' || operand!='*' || operand!='/') 
     printf("Wrong operation.Try again.\n"); 
}while(operand!='+' || operand!='-' || operand!='*' || operand!='/'); 

if(operand=='+') 
{ 
    printf("\nYou have chosen to add the numbers.\nThe result of the ADD is the inaginary number\n imz=(%f+%f) +(%f+%f)",z1.Rez,z2.Rez,z1.Imz,z2.Imz); 
} 
if(operand=='-') 
{ 

} 
if(operand=='*') 
{ 

} 
if(operand=='/') 
{ 

} 
system("pause"); 

return 0; 
} 

Пожалуйста, приложите любые предложения? Я застрял!

+1

Это впечатляет, как никто из вас не пришел к идее использовать отладчик для проверки значения 'operand' после вызова' getchar' в течение трех часов ...;) – mafso

+0

@mafso конечно 'getchar()' возвращает ' «\ n''. Лучше использовать с 'scanf ("% c ", & operand)' и получить '' '' '' '' 'и' 'right. – chux

+1

@chux: Спойлер! :) – mafso

ответ

4

if (operand!='+' || operand!='-' || operand!='*' || operand!='/')

Это утверждение всегда верно, потому что в большинстве один из четырех условий может быть ложным.

вы должны это написал:

if (operand!='+' && operand!='-' && operand!='*' && operand!='/')

ту же ошибку для цикла while: всегда верно, бесконечный цикл.


Кроме того, вы думаете, что ваш getchar неправильно, но ваш Printf не получил каких-либо аргументов, чтобы отобразить.

operand=getchar(); 
printf("operand=%c"); 

Должно быть:

operand=getchar(); 
printf("operand=%c", operand); 
+0

Нет, что не исправить проблему –

+1

О, ваше 'do {} while' утверждение всегда верно. Но на этот раз он должен существовать, когда у вас 'операнд' равен' + ',' -', '*' или '/'. Таким образом, это будет 'while (operand == '+' || operand == '-' || operand == '*' || operand == '/');' – Anton

0

Это код фиксированной

struct complex { float Rez, Imz; }; 

int main() 
{ 
    char operand; 
struct complex z1, z2; 
printf("give the Real part of the first imaginary number z1:\n"); 
scanf("%f", &z1.Rez); 
printf("give the Imaginary part of the first imaginary number z1: \n"); 
scanf("%f", &z1.Imz);  
printf("give the Real part of the second imaginary number z2: \n"); 
scanf("%f", &z2.Rez); 
printf("give the Imaginary part of the second imaginary number z2: \n"); 
scanf("%f", &z2.Imz); 
do 
{ 
    printf("Give + for ADD\nGive * for MULTIPLICATION\nGive - for SUBTRACTION\nGive/for DIVISION\n"); 
    operand=getchar(); 
    if (operand!='+' || operand!='-' || operand!='*' || operand!='/') 
     printf("Wrong operation.Try again.\n"); 
}while(operand=='+' || operand=='-' || operand=='*' || operand=='/'); 

if(operand=='+') 
{ 
    printf("\nYou have chosen to add the numbers.\nThe result of the ADD is the inaginary number\n imz=(%f+%f) +(%f+%f)",z1.Rez,z2.Rez,z1.Imz,z2.Imz); 
} 
if(operand=='-') 
{ 

} 
if(operand=='*') 
{ 

} 
if(operand=='/') 
{ 

} 
system("pause"); 

return 0; 
} 
+1

Это всегда будет печатать 'Неверная операция. снова. ', независимо от значения' operand', но, по крайней мере, цикл выходит в какой-то момент. +1 для вас. – Anton

-1

изменить делать, пока в этом и оно не спрашивай меня поставить символ это только заканчивается его кажется, что его игнорирование getchar не знает, почему

do 
{ 
    printf("Give + for ADD\nGive * for MULTIPLICATION\nGive - for SUBTRACTION\nGive/for DIVISION\n"); 
    operand=getchar(); 
} 
while(operand=='+'); 
+1

Попробуйте без цикла, посмотрите, действительно ли процессор выполняет инструкции. – Anton

+0

Я сделал это, и он просто распечатал выбор и закончил ... очень странно ... –

+1

Тогда это как-то связано с буфером ... Взгляните на этот вопрос: (http://stackoverflow.com/questions/4573457/how-to-flush-the-console-buffer) – Anton

Смежные вопросы