c++ - 变量不会从 C++ 中的用户输入改变
问题描述
我正在尝试在 C++ 控制台中为几何定理和代数中的其他公式创建多个计算器,并且由于一些奇怪的原因在程序开始时,选择一个选项时变量scene
不想更改(显示在数组之前calculators[]
,而不是转到勾股定理( scene 1
),控制台说,“按任意键继续......”然后关闭。
我已经尝试了switch()
andif()
语句来导航场景管理,但是我做错了什么?(顺便说一句,我仍然是 C++ 学习者,但我有其他编程语言经验)。
我在这里先向您的帮助表示感谢。
#include "stdafx.h"
#include <iostream>
#include <cmath>
int scene(0);
char calculators[3][25] =
{
"",
"Pythagorean Theorem",
"Homer's Formula"
};
void selection()
{
std::cout << "Enter a number to select a calculator." << std::endl; // Opening
for (int i = 1; i <= 2; i += 1) {
std::cout << "Option " << i << ": " << calculators[i] << std::endl;
}
}
void pTheorem()
{
int a;
int b;
std::cout << "Enter side a: ";
std::cin >> a;
std::cout << "Enter side b: ";
std::cin >> b;
std::cout << "Side length of c is " << sqrt(pow(a, 2) + pow(b, 2)) << std::endl;
}
int main()
{
switch(scene)
{
case 0:
selection();
std::cin >> scene;
std::cout << "You've selected the " << calculators[scene] << " Calculator" << std::endl;
break;
case 1:
pTheorem();
break;
}
return 0;
}
解决方案
您的主要问题是scene
已0
在开头(全局)本身声明和初始化。这将为您提供始终相同的开关case = 0
。更换scene
箱子内部是switch
行不通的。相反,您需要scene
在switch
.
int main()
{
selection();
int scene = 0;
std::cin >> scene;
switch(scene)
{
......
}
}
其次,使用std::string
而不是char数组并使用std::vector<>
/std::array
来存储它们。例如:
std::array<std::string,2> calculators =
{
"Pythagorean Theorem",
"Homer's Formula"
};
和for
循环可以是:
for (int i = 0; i < 2; ++i)
std::cout << "Option " << i+1 << ": " << calculators[i] << std::endl;
推荐阅读
- reactjs - 无法从组件中获取 redux 状态
- node-red - Node-Red中的状态机,如何?
- android - 如何从设置中获取数据并发送到此片段
- postgresql - 设置 GUC 参数或使用 PGOPTIONS 环境变量与 PgBouncer
- python - ctx.send() 不适用于播放音乐
- swiftui - SwiftUI 视图中更短的泛型语法
- winapi - 是否有任何 Win32 函数可用于从 CComboBoxEx 控件获取计数/项目数据?
- regex - 正则表达式 - 文本中的每次出现
- php - 无法使用 php 和 sql 创建表
- c++ - 无法在 Windows 上使用 make 命令编译 Makefile