我最近开始研究C ++,并且尝试通过一些操作来创建“计算器”。 但是我陷入了字符串26(cin >> select;),这似乎没有响应。为什么?
//CALCULATOR
#include <iostream>
using namespace std;
int main()
{
int start;
int choose;
int first;
int second;
int unic;
int result;
cout << "CALCULATOR (2 values)" << endl;
cout << "Click a botton to continue: " << endl;
cin >> start;
cout << "Write: " << endl;
cout << "- '1' for sum" << endl;
cout << "- '2' for subtraction" << endl;
cout << "- '3' for moltiplication" << endl;
cout << "- '4' for power of 2" << endl;
cout << "Your answer: " << endl;
cin >> choose;
cout << "________________________" << endl;
{
if (choose=1, 2, 3)
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
{
if (choose=1)
result = first + second;
}
{
if (choose=2)
result = first + second;
}
{
if (choose=3)
result = first * second;
}
{
if (choose=4)
cout << "Insert the value: " << endl;
cin >> unic;
result = unic * unic;
}
}
cout << "Your result is: " << result;
}
它没有给我任何错误,但是它继续执行我编写的所有“ cout”操作,而没有给我用“ cin”编写值的可能性。
答案 0 :(得分:1)
您的代码中有几个问题,
if (choose = 1, 2, 3){
...
// this doesn't work in C/C++
// change it into
if (choose == 1 || choose == 2 || choose == 3)
在条件(如果/否则或循环/同时)下有多行代码时,您将需要在花括号内显式阻止它们。因此,如果先阻止到此,则情况会发生变化
if (choose == 1 || choose == 2 || choose == 3){
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
...
嵌套if条件相同。
也没有理由接受输入。
如果您修复了所有错误,则应该获得如下代码->
//CALCULATOR
#include <iostream>
using namespace std;
int main()
{
int start;
int choose;
int first;
int second;
int unic;
int result;
cout << "CALCULATOR (2 values)" << endl;
cout << "Click a botton to continue: " << endl;
// cin >> start;
cout << "Write: " << endl;
cout << "- '1' for sum" << endl;
cout << "- '2' for subtraction" << endl;
cout << "- '3' for moltiplication" << endl;
cout << "- '4' for power of 2" << endl;
cout << "Your answer: " << endl;
cin >> choose;
cout << "________________________" << endl;
if (choose == 1 || choose == 2 || choose == 3){
cout << "Insert the first value: " << endl;
cin >> first;
cout << "Insert the second value: " << endl;
cin >> second;
if (choose == 1)
result = first + second;
if (choose == 2)
result = first + second;
if (choose == 3)
result = first * second;
}
if (choose == 4){
cout << "Insert the value: " << endl;
cin >> unic;
result = unic * unic;
}
cout << "Your result is: " << result << endl;
}
脚注:请使用给定的代码作为参考,并尝试仔细地了解基本知识。这样做很重要。