Problem for greenhorn

This is a discussion on Problem for greenhorn within the C++ Programming forums, part of the General Programming Boards category; Friends, I have just begun taking my first C++ class on-line and I am having problems with an if - ...

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    1

    Problem for greenhorn

    Friends,
    I have just begun taking my first C++ class on-line and I am having problems with an if - else error. It is driving me crazy. I am attaching my program and hopefully one of you pros can help me out. I think I'm close. Thanks...
    Freddyboy
    Code:
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int main()
    {
    
    	int num1, num2, answer;
    	char operand;
    
    	cout << "Please enter a number: ";
    	cin >> num1;
    	cout << "Now enter an operand: ";
    	cin >> operand;
    	cout << "Now enter a second number: ";
    	cin >> num2;
    
    	if (operand == '+')
    		answer = num1 + num2;
    		cout << "The answer is " << num1 << "+" << num2 << "=" << answer << endl;
    	if (operand == '-')
    		answer = num1 - num2;
    		cout << "The answer is " << num1 << "-" << num2 << "=" << answer << endl;
    	if (operand == '*')
    		answer = num1 * num2;
    		cout << "The answer is " << num1 << "*" << num2 << "=" << answer << endl;
    	if (operand == '/')
    		answer = num1 / num2;
    		cout << "The answer is " << num1 << "/" << num2 << "=" << answer << endl;
    	if (operand == '%')
    		answer = num1 % num2;
    		cout << "The answer is " << num1 << "%" << num2 << "=" << answer << endl;
    	else  
    		cout << "An invalid operator was entered" << endl;
    
    	return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You need curly braces. And remember that else only attaches to the one nearest if, so the invalid operator message will print every time that the operand isn't %.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 05:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 09:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 07:54 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21