Advertisement
DrAungWinHtut

calculator2.cpp

Jul 2nd, 2025
162
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 1 0
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.     float n1 = 0.0F;
  6.     float n2 = 0.0F;
  7.     int n11 = 0; // For integer division and modulus
  8.     int n22 = 0; // For integer division and modulus
  9.     float ans = 0.0F;
  10.     char ch = '\0'; //NULL
  11.     cout<<"Calculator App"<<endl;
  12.     cout<<"===================="<<endl;
  13.     cout<<"Please enter first number: ";
  14.     cin>>n1;
  15.     cout<<"Please enter second number: ";
  16.     cin>>n2;
  17.     cout<<"choose operation +,-,*,/,%: ";
  18.     cin>>ch;
  19.  
  20.     switch (ch) {
  21.     case '+':
  22.         cout << "You chose addition." << endl;
  23.         ans = n1 + n2;
  24.         break;
  25.  
  26.     case '-':
  27.         cout << "You chose subtraction." << endl;
  28.         ans = n1 - n2;
  29.         break;
  30.  
  31.     case '*':
  32.         cout << "You chose multiplication." << endl;
  33.         ans = n1 * n2;
  34.         break;
  35.  
  36.     case '/':      
  37.         cout << "You chose division." << endl;     
  38.         if (n1 == 0.0F && n2 == 0.0F) {
  39.             cout << "Error: Both numbers are zero!" << endl;
  40.             return 1; // Exit with error code
  41.         }
  42.         else if (n1 == 0.0F) {
  43.             cout << "Error: First number is zero!" << endl;
  44.             return 1; // Exit with error code
  45.         }
  46.        
  47.         else if(n2 == 0.0F) {
  48.             cout << "Error: Division by zero!" << endl;
  49.             return 1; // Exit with error code
  50.         }
  51.         else {
  52.             ans = n1 / n2; // Perform division
  53.         }
  54.         break;
  55.  
  56.     case '%':
  57.         cout << "You chose modulus." << endl;
  58.         n11 = static_cast<int>(n1); // Convert to integer for modulus
  59.         n22 = static_cast<int>(n2); // Convert to integer for modulus
  60.         if (n22 == 0) {
  61.             cout << "Error: Division by zero!" << endl;
  62.             return 1; // Exit with error code
  63.         }
  64.        
  65.         ans = n11 % n22; // Perform modulus
  66.         break;
  67.     default:
  68.         cout << "Invalid operation!" << endl;
  69.         return 1; // Exit with error code
  70.     }
  71.  
  72.  
  73.    
  74.  
  75.     cout<<"answer = "<<ans<<endl;
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement