【问题标题】:Variable not changing from user input in C++变量不会从 C++ 中的用户输入改变
【发布时间】:2018-11-26 09:41:06
【问题描述】:

我正尝试在 C++ 控制台中为 几何定理 和 代数中的其他公式创建多个计算器, 并且出于某些奇怪的原因在程序开始时,选择选项时,Console表示,“按任意键继续...” 并关闭。

我已尝试使用switch() 和if() 语句来导航场景管理,但我做错了什么? (顺便说一句,我仍然是 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;
}

【问题讨论】:

  • 将您的代码添加到问题中。
  • 使用std::string而不是char数组并使用std::vector&lt;&gt;来存储它们。
  • 对于发生的事情我感到非常抱歉,我在输入问题时不小心点击了“提交帖子”按钮。

标签: c++ arrays c++11 switch-statement global-variables


【解决方案1】:

您的主要问题是 scene 已在开头(全局)本身声明并初始化 0。这将始终为您提供相同的开关case = 0。在 switch 案例中更改 scene 将不起作用。相反,您需要在switch 之前输入scene。

int main()
{
    selection();
    int scene = 0;
    std::cin >> scene;
    switch(scene)
    {
        ......
    }
}

其次,使用std::string而不是char数组并使用std::vector&lt;&gt;/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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多