使用 cin 错误输入多个浮点数

Inputting multiple floats using cin ERROR

本文关键字:浮点数 输入 cin 错误 使用      更新时间:2023-10-16

我想连续输入 5 个float值,但程序无法正常工作

#include <iostream>
using namespace std;
int main()
{
    float v, i, vr, vl, vc, r, xl, xc, z;
    for (int i = 1; i <= 9; i++)
    {
        cout << "Enter the values of v,i,vr,vl,vc" << endl;
        cin >> v;
        cin >> i;
        cin >> vr;
        cin >> vl;
        cin >> vc;
        cout << endl << v << " " << i << " " << vr << " " << vl << " " << vc << endl;
    }
    return 0;
}

如果我尝试输入输入为 1.1 2.2 3.3 4.4 5.5 ,程序只接受四个值

输出为:
1.1 2 0.2 3.3 4.4

请告诉我哪里出错了,以及如何更正我的代码。

您将i用作外部作用域中的float,然后在内部作用域中使用it作为int。所以当你输入

1.1 2.2 3.3 4.4 5.5

cin>>v;
cin>>i; 
cin>>vr; 
cin>>vl; 
cin>>vc;

它只需要2.2 2,然后 vr 变量需要 0.2。

所以变量值变成

v=1.1
i=2
vr=0.2
vl=3.3
vc=4.4

因此留下 5.5,因为它需要 2.2 作为 2 个输入

溶液:

for循环变量更改为 j

代码中存在变量名称冲突:

float v, i, vr, vl, vc, r, xl, xc, z; // Here, variable "i" is declared as a floating-point variable
for (int i = 1; i <= 9; i++) // Here, "i" is declared again, this time as an int

当有多个同名但位于不同代码范围的变量时,编译器将使用此时作用域的本地变量。这会导致错误;您希望变量i存储输入2.2的值,但是,最局部的变量是 for 循环的计数器i。因此,编译器尝试将值存储在计数器中。由于计数器是int型,2.2被分解;柜台i商店2,vr存储0.2

这就是为什么编译器只接受 4 个值;第二个值输入分为 2 个变量。

要更正此问题,请更改 for 循环的计数器变量的名称:

float v, i, vr, vl, vc, r, xl, xc, z;
for (int j = 1; j <= 9; j++) // The name of the counter variable is changed from "i" to "j"
{
    cout << "Enter the values of v,i,vr,vl,vc" << endl;
    cin >> v;
    cin >> i;
    cin >> vr;
    cin >> vl;
    cin >> vc;
    cout << endl << v << " " << i << " " << vr << " " << vl << " " << vc << endl;
}

或者,将变量 i(范围在 for 循环之外的变量(的名称更改为其他名称:

float v, num, vr, vl, vc;
for (int i = 1; i <= 9; i++)
{
    cout << "Enter the values of v,j,vr,vl,vc" << endl;
    cin >> v;
    cin >> num;
    cin >> vr;
    cin >> vl;
    cin >> vc;
    cout << endl << v << " " << num << " " << vr << " " << vl << " " << vc << endl;
}