使用 cin 错误输入多个浮点数
Inputting multiple floats using cin ERROR
我想连续输入 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;
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用 std::cin 的输入仅适用于浮点数,仅当值尾随字母"e"(大写和小写)时
- 使用 cin 错误输入多个浮点数
- 在同一行中读取混合输入(字符串/浮点数),并将其存储在数组中
- 使用输入运算符读取浮点数C++
- 从输入流读取浮点数而不拖尾"E"
- C++ 仅使用 #iostream 检查输入是否为浮点数
- "Floating-point invalid operation"将浮点数输入到字符串流时
- 浮点数据意外地成功将 istream 输入为整数
- 输入第一个浮点数后出现奇数结果
- 向浮点数输入一个非数字值
- 如何检查输入的数字是否为整数不是浮点数
- 将时间输入转换为浮点数以启用C++中的数学函数
- 子类编辑控件的输入验证以仅接受浮点数
- C++ 向量输入<float>而不以非浮点数结尾
- 检查整个输入是否是浮点数