-2

my code doesn't return double value z, instead returns only 1, why?

#include <iostream>
#include <fstream>

using namespace std;
double road(int s, int v, int max )
{
    double t;
    t = (s/v);
    return t;
}
int main()
{
    int s[2]={0};
    int v[2]={0};
    int max;
    double z; // result of function
    ifstream fd;
    fd.open("u1.txt");
    fd >> max;
    for (int i = 0; i < 2; i++)
    {
        fd >> s[i] >> v[i];
        z = road( s[i], v[i], max );
        cout << z << " ";
    }

    fd.close();
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    Your function *does* return a `double`. You can tell because you declared its return type to be `double`. – Kerrek SB Nov 12 '15 at 13:27
  • The expression `s/v` evaluates to `int`. No matter whether you assign it to a double, it remains an `int`! – Paolo M Nov 12 '15 at 13:27
  • Got the idea, changeddouble road(int s, int v, int max ) to double road(double s, double v, int max ), thanks guys – ParanoidParrot Nov 12 '15 at 13:29

1 Answers1

0

Try to change your method like

double road(int s, int v, int max )
{
    double t;
    t = (s/(double)v);
    return t;
}

int/int will result in a integer. So you need to cast the numerator or denominator as double.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331