如何让我的答案看起来像小数

How to make my answers appear as decimals?

本文关键字:看起来 小数 答案 我的      更新时间:2023-10-16

我已经阅读了我的c++书的前50页左右,并掌握了我试图创建一个程序从一次计算圆的两次测量,这就是我想出了:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    string op;
    int r;
    int a;
    int d;
    int val;
    cout << "This program aims to calculate two measurements of a cicle from one measurement" << endl;
    cout << "Enter the measurement you wish to input from a choice of r, d or a" << endl;
    cin >> op;
    cout << "Please enter the value of this measurement" << endl;
    cin >> val;
    if (op == "r") {
        a = val * val * 3.14;
        d = val * 2;
        r = val;
    }
    if (op == "d") {
        a = val / 2 * val / 2 * 3.14;
        d = val;
        r = val / 2;
    }
    if (op == "a"){
        a = val;
        d = (sqrt(val / 3.14)) * 2;
        r = (sqrt(val / 3.14));
    }
    cout << "The area is " << endl;
    cout << std::setprecision(3) << a << endl;
    cout << "The diameter is  " << endl;
    cout << std::setprecision(3) << d << endl;
    cout << "The radius is " << endl;
    cout << std::setprecision(3) << r << endl;
}

我的问题是,我的答案都没有小数,正如你可以看到的,我已经试图纳入"setprecision",但它没有工作。

int替换为double:

int r;
int a;
int d;
int val;

std::set_precision仅在应用于浮点类型(如floatdouble)时执行您所期望的操作。我怀疑,如果您使用这些类型之一而不是int s

,您的大多数问题将得到解决。