簡體   English   中英

我如何獲得“ .00”格式的數字?

[英]How would I get a number in '.00' form?

我是C ++的新手,並編寫了一個簡單的GPA計算器程序。
它基本上要求您擁有的課程數量,並取每個課程的分數。
然后將字母等級轉換為數字。
最后,它對數值等級求和並求平均值。
我的問題是,如何將GPA結果精確轉換為4.00、3.00、2.00等格式?

#include <iostream>
using namespace std;

int main(){
    int grades_size;
    cout << "Enter the number of classes you are taking: ";
    cin >> grades_size;

    int *grades;
    grades = new int[grades_size];
    float *conversion;
    conversion = new float[grades_size];

    float sum = 0;

    cout << endl << "Enter your grade percentage of each class as a number 0-100." << endl;

    for (int i = 0; i < grades_size; i++) {
        cout << "Grade " << i + 1 << ": ";
        cin >> grades[i];

        if (grades[i] <= 100 && grades[i] >= 90) {
            conversion[i] = 4.00;
        } else if (grades[i] < 90 && grades[i] >= 80) {
            conversion[i] = 3.00;
        } else if (grades[i] < 80 && grades[i] >= 70) {
            conversion[i] = 2.00;
        } else if (grades[i] < 70 && grades[i] >= 60) {
            conversion[i] = 1.00;
        } else if (grades[i] < 60 && grades[i] >= 0) {
            conversion[i] = 0.00;
        }

        sum += conversion[i];
    }

    float GPA = sum / grades_size;
    cout << endl << "--- Your GPA is: " << GPA;
}

std :: setprecision (在iomanip標頭中)以及std :: fixed (已經包括在iostream中)可能在這里使用。

setprecision:設置打印浮點值時的小數精度。

固定:浮點值以固定符號打印。 與setprecision一起使用時,打印的數字總是那么長。

#include <iomanip> // std::setprecision
...
cout << endl << "--- Your GPA is: " << std::fixed << std::setprecision(2) << GPA;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM