这个程序有什么问题,它终止了?
What's wrong with this program, it terminates?
以下程序在计算选择后终止,并且不会再发生任何操作。所以我的问题是我做错了什么?请有人检查此程序并通知我我的错误。该程序是一个计算器,它要求用户选择计算方法,即加法,除法或乘法等,然后在计算后显示结果图:http://i43.tinypic.com/2hykpjp.png 请原谅我,因为我是 C 编程的新手。
main()
{
// declaration
int add,sub,mul,div,selection;
float a,b,c;
// prompt user to select a method
cout << "Calculator, which performs addition,subtraction,multiplication and division: add,sub,mul,div";
cout << "Please enter your selection (for example: mul): ";
cin >> selection;
if (selection = add)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a + b;
// result
cout << "Answer: " << c;
}
if (selection == sub)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a - b;
// result
cout << "Answer: " << c;
}
if (selection == mul)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a * b;
// result
cout << "Answer: " << c;
}
if (selection == div)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a / b;
// result
cout << "Answer: " << c;
}
}
您尚未在此处初始化任何内容:
int add,sub,mul,div,selection;
你使用cin >> selection;
取selection
的值,但这些东西应该意味着什么:
if (selection = add)
if (selection == sub)
if (selection == mul)
if (selection == div)
具有存储类auto
的变量不会初始化为任何默认值。
根据运行程序的示例,您要做的是输入字符串,例如 add,然后比较它们。你在程序中实际做的是选择、加法、子等是整数变量,只能用于存储整数。
您必须将 select 声明为字符串变量,并将其值与字符串常量进行比较,如下所示:
string selection;
然后:
if (selection == "add")
下一行没有初始化。
int add,sub,mul,div,selection;
使用唯一值初始化这些变量(例如 0 表示添加,1 表示 sub)。另外,在比较中
selection = add
用
selection == add
使用else if
而不是分隔 if。它将提高性能。在您的情况下,它将比较每个条件。它显示为一个示例。
if (selection = add)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a + b;
// result
cout << "Answer: " << c;
}
else if (selection == sub)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a - b;
// result
cout << "Answer: " << c;
}
//Rest of your program.
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在抛出 'std::invalid_argument' 的实例后终止调用 what(): stoi (找不到问题所在)
- C++程序问题:抛出'std::invalid_argument'实例后终止调用
- 可变参数模板中递归模板函数的终止问题
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- 而循环不工作终止问题
- 而循环终止问题
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- CPP-Netlib 问题,在抛出 'boost::exception_detail::clone_impl 的实例后调用终止
- 通过 -1 终止时出现问题
- 这个程序有什么问题,它终止了?
- 和野兔模拟终止问题
- 程序在输入开尔文或摄氏后终止?(我的代码有什么问题?
- 如果应用程序存在内存泄漏,是否在终止时解决这些问题