简体   繁体   English

C ++整数部分的数量非常多

[英]C++ Integer Division giving very large number

so I'm currently writing an assignment for my data structures class that's giving me a headache in the most basic place possible. 所以我目前正在为我的数据结构类编写一个作业,这使我在最基本的地方头疼。 We're working on the Hungtington-Hill method in conjunction with priority queues, and when I try and do my simple division to get the "priority" which is equal to the population of a state divided by the geometric mean, I'm getting really large numbers. 我们正在将Hungtington-Hill方法与优先级队列结合使用,当我尝试进行简单除法以获得“优先级”时,“优先级”等于一个州的人口除以几何平均值,就得到了确实很大。 The vars and method inside my state class look like this: 状态类中的var和方法如下所示:

class State{
 private:
    string state;
    int pop;
    int reps;
    double priority;
};
void State::calculatePriority(){
    double temp = (double)reps * ((double)reps + 1.0);
    priority = (double)pop/sqrt(temp);
}

The method calculatePriority() gives me crazy output, where it'll read in like this: 方法calculatePriority()给了我疯狂的输出,它将像这样读取:

State: California 州:加利福尼亚

2010 Census Population: 37253956 2010年人口普查人口:37253956

Representatives: 1 代表人数:1

Priority: 0 优先级:0

And post calculatePriority() I get this: 然后发布calculatePriority(),我得到以下信息:

State: California 州:加利福尼亚

2010 Census Population: 37253956 2010年人口普查人口:37253956

Representatives: 1 代表人数:1

Priority: 2.63425e+07 优先级:2.63425e + 07

Is there a logical mistake I'm making here? 我在这里犯逻辑错误吗? I'm not sure what the issue is. 我不确定是什么问题。 It may be with the sqrt() method I am not sure. 我可能不确定sqrt()方法。 I at first thought it was because of the (double) cast, so I changed all the vars to doubles, but I encountered the same issue. 起初我以为是因为(double)类型转换,所以我将所有var都更改为double,但是遇到了相同的问题。

The result is not that large, it's actually 2.63425e+07 ≈ 26342524 , which is the exact result of your calculation: 结果并不算大,实际上是2.63425e+07 ≈ 26342524 ,这是您计算的准确结果:

double temp = (double)reps * ((double)reps + 1.0); // = 2
priority = (double)pop/sqrt(temp); // = (37253956 / 1.41421) = 26342524

There is nothing wrong with your program :) 您的程序没有错:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM