C++,函数不返回双精度

C++, function doesn't return double

本文关键字:返回 双精度 函数 C++      更新时间:2023-10-16

我的代码没有返回双值z,而是只返回1,为什么?

#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;
}

尝试像一样更改方法

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

int/int将产生一个整数。所以你需要将分子或分母转换为二重。