我如何使其显示小数

How do i make it show decimals

本文关键字:小数 显示 何使其      更新时间:2023-10-16

我一直在观看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;

如果要显示小数,则必须使用其他数据类型。
尝试doublefloat

之类的东西

示例:

 double w = x*y;
 double c = x + y;
 double v = x - y;
 double q = x / y;

这应该很好。
如果您需要有关其他数据类型的更多信息,请查看以下内容:链接