5.4.4 do-while语句

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qit1314/article/details/90136927

书中页数:P169
代码名称:doWhile.cc

//doWhile.cc  guess.cc
#include <iostream>
using std::cin; using std::cout; using std::endl;

#include <string>
using std::string;

int main()
{
    // repeatedly ask the user for a pair of numbers to sum
    string rsp;  // used in the condition; can't be defined inside the do
    do {
        cout << "please enter two values: ";
        int val1 = 0, val2 = 0;
        cin  >> val1 >> val2;
        cout << "The sum of " << val1 << " and " << val2
             << " = " << val1 + val2 << "\n\n"
             << "More? Enter yes or no: ";
        cin  >> rsp;
    } while (!rsp.empty() && rsp[0] != 'n');

	cout << endl;

	return 0;
}
//guess.cc
#include <iostream>
using std::cin; using std::cout; using std::endl;

int main()
{
	do {
		cout << "Guess a number between 0 and 9" << endl;
		unsigned i, mynum = 7;
		cin >> i;

		if (i == mynum) {
			cout << "Congrats you guessed right!" << endl;
			break;
		} else
			if (i < mynum)
				cout << "too low" << endl;
			else
				cout << "too high" << endl;

		if (i != mynum)
			if (i < mynum)
				cout << "too low" << endl;
			else
				cout << "too high" << endl;
		else {
			cout << "Congrats you guessed right!" << endl;
			break;
		}
	} while (true);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qit1314/article/details/90136927