无法正确执行While循环

时间:2016-11-11 08:17:02

标签: c++

我正在尝试做一个while循环。我已经尝试了很长时间,但仍然无法弄清楚这一点。

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
char input;
double voltage, current;

while ((input = 'Y'))
{
    cout << "Enter the voltage: ";
    cin >> voltage;
    cout << "Enter the current: ";
    cin >> current;

    cout << "The resistance is " << voltage/current << endl;

    cout << "Do you wish to continue? [Y/N]";
    cin >> input;
}
}

输入&#39; Y&#39;以外的其他变量仍会导致代码循环。做// while((输入==&#39; Y&#39;))不给我输出

1 个答案:

答案 0 :(得分:1)

问题在于您进入循环的第一次时间,input没有值。这可以通过在声明中给它一个初始值来修复

int main()
{
char input = 'Y';
double voltage, current;

while (input == 'Y')
{

然后,您仍然遇到用户可能在循环结束时输入'y'而不是'Y'的问题。我们将此作为学生的练习。

相关问题