C++年龄无法正确显示
C++ age won't display properly
我的代码有什么问题?它没有显示正确的年龄?例如,如果我输入 1990 作为我的生日,它应该显示 25 作为我的年龄,但它显示 1025;
#include <iostream>
int main()
{
long unsigned x, year;
long unsigned z;
year = 2015;
std::cout << "Year of Birth: ";
std::cin.get();
std::cin >> x;
std::cin.get();
z = year - x;
std::cout << "Your age is " << z << std::endl;
std::cin.get();
std::cout <<" /n";
return 0;
}
删除@user2899162提到的每个std::cin.get()
实例,/n
不会打印新行,n
会打印。
编辑的代码:
#include <iostream>
int main()
{
long unsigned x, year;
long unsigned z;
year = 2015;
std::cout << "Year of Birth: ";
std::cin >> x;
z = year - x;
std::cout << "Your age is " << z << std::endl;
std::cout <<"n";
return 0;
}
请在您不确定的操作后打印变量的值,自己删除这些小错误。
这是因为语句
cin.get();
line:12
.
cin.get();
将按住屏幕,直到用户点击某个键,然后才继续执行程序的其余部分。
因此,如果用户输入 1992 年作为他的出生年份,则第一个键盘点击"1"将被cin.get()
使用,cin>>x
将只在 x 中存储 992。
溶液:删除cin.get()
干杯
正如其他人之前回答的那样,删除 std::cin.get() 将解决您的问题对于换行符,您也可以使用 std::endl。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- std::strftime 在 Windows 中使用 GMTIME 将时区 UTC 显示为 UTC+1