0

Hello I need a simple explanation in while looping division I don't know if my code in division is correct or not the results I got seems wrong from where I expect the result to be 10/5=2 but instead I got 10/5=0
Please do help me in my code do point out if there is anything wrong in my division code

Here's my code below:


#include <iostream>
using namespace std;
                        
int number, amt, chc, total;

int main() {
    int amt = 0;
    
    cout << "Welcome again User!\n";
    cout << "______________________________________________________________\n" << endl;
    cout << "Mathematical Operations:\n\n";
     
    cout << "\t[1]-Addition" << endl;
    cout << "\t[2]-Division\n" << endl;    
    
    cout << "______________________________________________________________\n" << endl;
    
    cout << "Type the number corresponding to your chosen operation: ";
    cin >> chc;
    
  switch (chc) {
    
  case 1:
    system ("cls");
    
    cout << "\n\n\tOperation chosen: Addition";
    
    cout << "\n______________________________________________________________" << endl;
    
    cout << "\n\Input positive numbers to use the operation and input a negative number to end the operation.\n\n";
    
    cout << "Enter your number: ";
    cin >> number;
    
    while (number >= 0) {
        // add all positive numbers
        amt += number;
        
        // take input again if the number is positive
        cout << "Enter another number: ";
        cin >> number;
    }
    
        // display the sum
    cout << "\nThe sum of all the numbers is: " << amt << endl;
    break;
    
  
  case 2:
    system ("cls");
    cout << "\n\n\tOperation chosen: Division";
    
    cout << "\n______________________________________________________________" << endl;
    
    cout << "\n\Input positive numbers to use the operation and input a negative number to end the operation.\n\n";
    
    cout << "Enter your number: ";
    cin >> number;
    
    while (number >= 0) {
        // divide all positive numbers
        amt /= number; //Not sure if correct
        
        // take input again if the number is positive
        cout << "Enter another number: ";
        cin >> number;
    }
    
        // display the average
    cout << "\nThe average of all the numbers is: " << amt << endl;
    break;
    
  default:
    system ("cls");
    cout << "\n\n\tInput invalid, please try again.";
  } 
  
  return 0;
}
  • What is the output? What are you expecting? – Irelia Mar 19 '22 at 04:11
  • Your while loop explicitly allows division by zero. Why? What is the value of `amt`? What is the _type_ of all your variables? You've shown a fragment of a program. Minimal reproducible example is required. – paddy Mar 19 '22 at 04:22
  • i was expecting 10/5=2 but the result i got was 10/5=0 – Sweet Ehanag Mar 19 '22 at 04:25

0 Answers0