M
M
Mark Zuckenberg2019-01-30 16:48:13
C++ / C#
Mark Zuckenberg, 2019-01-30 16:48:13

Why does float round up?

I have a program, I need it to calculate the average score, it calculates it, but at the same time it rounds even though I specified a float

#include <iostream>
#include <math.h>
#include <string>
using namespace std;

class Student {
  string surname;
  string name;
  string patronymic;
  
  public:
  int informatics;
  int algorithmization;
  int algorithm;
  
  float sum() {
    return ((informatics+algorithmization+algorithm)/3);
  }
  float vyvod() {
    cout << "Информация о студенте";
    cout << "\nИмя: " << name;
    cout << "\nФамилия: " << surname;
    cout << "\nОтчество: " << patronymic;
    cout << "\nОценка по информатике: " << informatics;
    cout << "\nОценка по алгоритмизации: " << algorithmization;
    cout << "\nОценка по теории алгоритмов: " << algorithm;
    cout << "\nСредний бал всех оценок: " << sum();
    return 0;
  };
  
  Student(string surname_n, string name_n, string patronymic_n, int informatics_n, int algorithmization_n, int algorithm_n) {
    surname = surname_n;
        name = name_n;
        patronymic = patronymic_n;
        informatics = informatics_n;
        algorithmization = algorithmization_n;
        algorithm = algorithm_n;
  };
  Student() {};
  ~Student() {};
  string getSurname() {return surname;}
    string getName() {return name;}
    string getPatronymic() {return patronymic;}
    void setSurname(string surname_n) { surname = surname_n; }
    void setName(string name_n) { name = name_n; }
    void setPatronymic(string patronymic_n) { patronymic = patronymic_n; }
};

int main() {
  Student s1("Корегин", "Александр", "Алексеевич",5,4,3);
  s1.vyvod();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2019-01-30
@0xD34F

There is no float rounding. The computed value is initially an integer - because all parts of the expression are integers. Replace /3with /3.0.

D
Dmitry, 2019-01-30
@dnovikoff

float(informatics+algorithmization+algorithm)/3;
In your example, int is first calculated (rounded up), and then converted to float.
Convert sum to float before division

W
Wexter, 2019-01-30
@Wexter

Because all your operations are performed with integers, divide by a number with a dot

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question