簡體   English   中英

功能計算

[英]Calculation in function

double cost_factor(int num_of_sections, int num_of_students) {
    double cost;
    cost = 35 * num_of_sections / num_of_students;
    printf("Cost = %.2lf\n", cost);
    return cost;

}

無論我為num_of_sections和num_of_students輸入什么,我得到的返回值為1.00。 如果我輸入11(num_of_sections)和364(num_of_students),我得到1.00,但是它應該是1.06。 有誰能識別他們的錯誤?

你用整數做數學。 所以你將得到整數值。

const = 35 * num_of_sections / num_of_students 

即使cost是雙倍的,因為所有組件都是ints因此會給你一個int。

您將需要對值進行類型轉換以獲得double輸出

cont = 35.0 * (double)num_of_sections /  (double)num_of_students;

請注意,過度殺戮,足以將等值中的一個值提升為雙倍。

cont = 35.0 * num_of_sections / num_of_students;

然后,C會自動為您推廣其他值。

除以兩個整數會返回一個整數,並刪除小數部分。 試試這個:

cost = 35.0 * num_of_sections / num_of_students;

35.0是雙字面而不是整數字面值。 這將導致表達式35.0 * num_of_sections被計算為double * double (在計算之前int被轉換為double ),然后除法也將使用兩個雙精度進行。

問題是將num_of_studentsnum_of_sections提升一倍,以便可以正確計算cost

double cost(double num_of_students, double num_of_sections)

查看所有操作:它們都只涉及整數,因此C進行整數運算。 解決的最快方法是讓35一個double ,這將導致推廣double其他操作數(如果有的話在操作的操作數為double另一個推動)。

所以你可以這樣做:

cost = ((double)35) * num_of_sections / num_of_students;

或更好,

cost = 35. * num_of_sections / num_of_students;

(有些人更喜歡35.0 ,但是35.結尾處的點足以指定它是double字面值;而35單獨使用,而是用作int文字)

暫無
暫無

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

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