首页 > 解决方案 > 变量不会从 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;
}

标签: c++arraysc++11switch-statementglobal-variables

解决方案


您的主要问题是scene0在开头(全局)本身声明和初始化。这将为您提供始终相同的开关case = 0。更换scene箱子内部是switch行不通的。相反,您需要sceneswitch.

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;

推荐阅读