【发布时间】:2014-03-22 03:53:44
【问题描述】:
我是一个非常新手的程序员,所以我不太了解编写代码来保护应用程序。基本上,我创建了一个 basicMath.h 文件并创建了一个 do while 循环来制作一个非常基本的控制台计算器(只有两个浮点数通过函数)。我使用一系列 if 和 else if 语句来确定用户想要做什么。 (1.add, 2.subtract, 3.multiply, 4.divide) 我使用 else { cout
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
【问题讨论】:
-
当然有办法——如果你发布你的代码,我们也许可以告诉你哪里出错了
-
试试
if (cin >> options) { // input was a number } else { // input was something else. } -
我不确定我明白你的意思吗?我应该在哪里添加 if ( cin >> options)?在我开始原始 if 语句之前?
-
即把
cin >> options替换成上面那个if语句。 -
+1 表示关注用户输入验证,尽管是新手程序员。
标签: c++