2013-03-07 81 views
-2

我只是從C移到C++,並且正在嘗試構建計算器。詮釋'結果'不會初始化與數學運算。邏輯是,根據操作的''將有一個不同的值分配給'結果'。這似乎並不奏效。爲什麼我的變量沒有初始化?

#include<iostream> 
#include<cstring> 
#include<cmath> 
using namespace std; 

int main() 
{ 
    int n1, n2; 
    char s,r; 
    int result = 0; 
    cout<< "Enter a calculation? (y/n)"<<endl; 
    cin>>r; 
    while(r=='y') 
    { 
     cout <<"Enter the first number"<<endl; 
     cin>>n1; 
     cout<<"Enter the operator"<<endl; 
     cin>>s; 
     cout<<"Enter the second number"<<endl; 
     cin>>n2; 

     if ('s' == '*') 
     { 
      result = n1*n2; 
     } 
     if ('s' =='+') 
     { 
      result = n1+n2; 
     } 

     if ('s' =='-') 
     { 
      result = n1-n2; 
     } 

     if ('s' =='/') 
     { 
      result = n1/n2; 
     } 
     cout << result<<endl; 
     cout<< "Enter a calculation? (y/n)"<<endl; 
     cin>>r; 
    } 
    return 0; 
} 
+0

你怎麼知道*** ***結果未初始化?你有什麼證據?你的投入是什麼,你期望什麼產出與你實際看到的是什麼? – abelenky 2013-03-07 17:40:54

+0

*「這似乎不起作用。」*爲什麼?有什麼問題? – m0skit0 2013-03-07 17:41:28

+1

Aww,這個傷害。 – 2013-03-07 17:42:36

回答

13

您必須與s進行比較而不是's'。所以,你的代碼看起來應該像

if (s == '*') 
{ 
    result = n1*n2; 
} 

代碼

if ('s' == '*') 

字符s與字符*,這始終是假的。

3

@OlafDietsche說得對。

我還建議切換到switch-case聲明:

switch(s) 
{ 
    case '*': result = n1*n2; break; 
    case '+': result = n1+n2; break; 
    case '-': result = n1-n2; break; 
    case '/': result = n1/n2; break; 
} 
+0

+1非常好的建議。 – 2013-03-07 17:55:19