[英]Make this program display an error message if a negative number is entered, and prompt for a new positive number?
如果用户输入负数,然后提示输入新的正数,如何使该程序显示错误消息? 由于这是十进制到十六进制的计算器,因此用户不应输入负数。
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
bool play_again;
do
{
int dec_num, r;
string hexdec_num = "";
char hex[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
cout << "\n\n Convert a decimal number to hexadecimal number:\n";
cout << "---------------------------------------------------\n";
cout << " Input a decimal number: ";
cin >> dec_num;
while (dec_num > 0)
{
r = dec_num % 16;
hexdec_num = hex[r] + hexdec_num;
dec_num = dec_num / 16;
}
cout << " The hexadecimal number is : " << hexdec_num << "\n";
while (true) // loop asking user
{
string user_input;
cout << "again? ('y', 'n'):" << endl;
cin >> user_input;
if (user_input == "y")
{
play_again = true;
break;
}
else if (user_input == "n")
{
play_again = false;
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
} while (play_again);
}
您可以通过在cin >> dec_num;
后面添加一个 if 语句来解决这个问题cin >> dec_num;
所以你可以检查它的值是否低于0
或没有
在cin >> dec_num;
行下添加这一行cin >> dec_num;
:
if (dec_num < 0)
{
//do whatever you want here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.