Hi. This program has a function that divides an unsigned arg by another unsigned arg. I want it to only keep outputting "I'm really upset" after the first time it outputs "I'm really upset". Right now it outputs as

5
0
I'm really upset
6
Press any key to continue . . .

I want it to output like this

5
0
I'm really upset
I'm really upset
Press any key to continue . . .
#include<iostream>
using namespace std;

void divide(unsigned a, unsigned b);

int main(){
	
	divide(100,20);
	divide(3, 4);
	divide(12, 0);
	divide(18,3);
	system("pause");

}
	void divide(unsigned a, unsigned b){
	if(b==0)
		cout << "I'm really upset" << endl;
		
	else
		cout << a / b << endl;
	}

Hint: use a bool variable to keep track of whether you've been upset before. Check whether or not b is zero OR the bool variable is set to true.

alright i'll see what I can do thanks for the hint!

I changed the function to

void divide(unsigned a, unsigned b){
	bool c;
	if(c=true){
		cout << "I'm really upset" << endl;
		c = true;
	}

	if(b==0){
		cout << "I'm really upset" << endl;
		c = true;
	}
	else
		cout << a / b << endl;
	}

It's not complete but is this the right idea?

See if you can see the problem with if(c[B]=[/B]true) If your two if statements are doing the same thing, why not combine them. The OR in my last post was a clue.

A minor thing: you should initialize c to false explicitly when you define it, just to be sure.

When i put the function as this

void divide(unsigned a, unsigned b){
	bool c;
	if(c=true){
		cout << "I'm really upset" << endl;
		c = true;
	}
	else if(b=0){
		cout << "I'm really upset" << endl;
		c = true;
	}
	else
		cout << a / b << endl;
	}

it keeps saying it is upset when it is not suppose to.

You need to have c==true (really you only need if(c) because c is a boolean variable) Same for b=0, change it back to b==0

Again, rather than have two blocks in your if do the same thing, use || (or) in the one if statement. "If C is true OR b equals 0"

Ok now I have it as

void divide(unsigned a, unsigned b){
	bool c = false;
	if(b==0 || c==true){
		cout << "I'm really upset" << endl;
		c == true;
	}
	else
		cout << a / b << endl;
		c == false;
	}

but I still don't know how I would keep the bool true once it becomes true.

Can you think of a way (a keyword) to maintain a variable between function calls?

Also, delete line 9 (you don't need to make it false if it already is) and change line 5 to an assignment operator (single equals). Review the difference between assignment(=) and comparison(==) it's important.

alright so it should be

static bool c = false;

right?

Yes! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.