2015-01-23 6 views
0

첫 번째 cs 과정에 대해이 작업을 수행해야합니다. 연산자와 값을 취하여 합계를 계산하는 기본 계산기입니다 (총 시작점은 0).C++ char 변수를 값과 비교할 수 없습니다.

#include <iostream> 

using namespace std; 

int main() 
{ 
    char oprtr; 
    float value, total = 0.0; 

    cin >> oprtr >> value; 

    while (oprtr != "q") 
    { 
     if (oprtr == "+") 
      total += value; 
     else if (oprtr == "-") 
      total -= value; 
    } 
} 

아직 끝나지 않았지만 이미 문제가 있습니다. "char 값을 int 값과 비교하는 것을 금지합니다"라는 내용의 오류가 발생합니다.

답변

9

큰 따옴표 ("q")는 문자열입니다. 작은 따옴표 ('q')는 문자 용입니다. 그래서

:

while (oprtr != 'q') 
{ 
    if (oprtr == '+') 
     total += value; 
    else if (oprtr == '-') 
     total -= value; 
} 
1

CharCharacter 의미하고 작은 따옴표에게 이들에 대한 ''를 사용해야합니다, 따옴표 "" 문자열을위한 것입니다.

리터럴 문자열의 (a const char)에 문자를 비교하기 위해 시도하고 있기 때문에이 오류가 발생하는 이유는

, 당신이 얻고있는 정확한 오류는 다음과 같습니다

Operand types are incompatible ("char" and "const char").

아래의 코드

#include <iostream> 

using namespace std; 

int main() 
{ 
    char oprtr; 
    float value, total = 0.0; 

    cin >> oprtr >> value; 

    while (oprtr != 'q') 
    { 
     if (oprtr == '+') 
      total += value; 
     else if (oprtr == '-') 
      total -= value; 
    } 
} 
-3

문자열 길이 비교는 문자열에 더 많은 문자가 포함되어 있는지 확인할 수 있으므로 C 프로그래밍의 일반적인 기능입니다. 이것은 데이터 정렬에 매우 유용합니다. 문자열 비교에는 특별한 기능이 필요합니다. ! = 또는 ==를 사용하지 마십시오.

http://www.techonthenet.com/c_language/standard_library_functions/string_h/strcmp.php

+2

이 질문에 대한 답변을 제공하지 않으므로 답하기 전에 조사를 수행하십시오. – cybermonkey

1

그리고 당신은 한 번 문 또는 식을 읽기 때문에 캐릭터가 'Q'와 같지 않은 동안 또한, 루프 당신을위한 필요가 없습니다. 기본적으로 하나의 작업을 수행해야합니다. 또한 switch는 여러 if 대신 리터럴을 비교하는 데 매우 유용한 구조입니다. 그래서 나는 그것을 단순화 할 것이다.

#include <iostream> 

using namespace std; 

int main(){ 
    char op; 
    float value, total = 0.0; 

    cin >> op >> value; 
    //it is important at this stage to check for errors, as they are most likely 
    //to occur. 
    if(!cin){ 
     cerr << "Error: format unknown! \n"; //basic error handled here, the prog outputs the error 
    } 

    //now perform the calculation 
    switch(op){ 
     case '+': total += value; 
     break; 
     case '-' : total -= value; 
     break; 
     case 'q' : break;  //i presume q is your quit character 
     default: /*unknown character*/ cerr << "Unknown operation! \n"; 
    } 

    cout << "Total: "<<total << endl; 

    return 0; 
} 

이것은 기본적으로 하나의 표현식을 읽어서 합계에 더한다. 원하는만큼 오래 읽도록 수정할 수 있습니다.

관련 문제