我如何使其显示小数
How do i make it show decimals
我一直在观看YouTube和Internet上的不同指南,并认为制作计算器会很有趣,因为我已经看到很多人这样做,这就是我开始的。它可以正常工作,但我希望它也能够显示小数。所有答案均值得赞赏。(我有一堆#include,但忽略了)
#include <iostream>
#include <limits>
#include <cstdio>
#include <tchar.h>
#include <conio.h>
using namespace std;
int main()
{
std::cout << "My first caclulatornPlease enter your first number: ";
int x, y;
std::cin >> x;
std::cout << "Please enter the other number: ";
std::cin >> y;
int w = x*y;
int c = x + y;
int v = x - y;
int q = x / y;
std::cout << "nNumbers multiplied: " << w << endl;
std::cout << "nNumbers added together: " << c << endl;
std::cout << "nNumbers subtracted: " << v << endl;
std::cout << "nNumbers divided: " << q << endl;
_tprintf(_T("Press any key to exit "));
while (_kbhit() ) _gettch();
_gettch();
return 0;
}
您的所有计算都是用整数数学完成的,因此不涉及小数(所有值都截断)。您可以更改使用double
的代码,但最终将获得大量的小数点,因此最好使用setprecision
圆形,例如:
double w = x*y;
double c = x + y;
double v = x - y;
double q = x / y;
std::cout << "nNumbers multiplied: " << setprecision(2) << w << endl;
std::cout << "nNumbers divided: " << setprecision(2) << q << endl;
如果要显示小数,则必须使用其他数据类型。
尝试double
或float
。
示例:
double w = x*y;
double c = x + y;
double v = x - y;
double q = x / y;
这应该很好。
如果您需要有关其他数据类型的更多信息,请查看以下内容:链接
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++将浮点指针值舍入为小数位数
- 如何设置数字格式以显示C 中的所有小数位数
- C 圆形为1个小数,显示2个小数
- STD :: SetPrecision不显示尾随的小数
- 我如何使其显示小数
- C++ - 为什么我的cout代码显示小数不一致
- 关于以二进制存储并显示其小数
- C++不显示小数位数的数字
- 显示带小数位数的数字,而不是整数
- 使用Float或Double类型时不显示小数
- 小数未正确显示 C++
- 如何在 8.th 小数之后擦除/不显示浮点小数
- 从二进制文件读取双精度(到类中)-小数不显示
- 在小数后显示有限的位数
- 在c++中货币计数器中没有显示小数