2015-02-17 50 views
1

我有問題,使用模數試圖除以小數。我選擇了fmod來選擇3和4,但是當選擇了3和4時,選擇了英寸後程序將停止工作。我希望保持模數,因爲就像我們在課堂上所獲得的那樣,但我我也開放其他方式。嘗試使用模數或fmod,但兩者都給我的程序問題?

int inches, choice, feet, yards; 
float centimeters, meters; 
float locentimeters, lometers; 
int meternum, centnum; 
meternum = 39.370; 
centnum = .39370; 



cout << "Display the entered length in:\n" 
    << "1.\tfeet\n" 
    << "2.\tyards\n" 
    << "3.\tcentimeters\n" 
    << "4.\tmeters\n\n" 
    << "Enter your choice:\n"; 
cin >> choice; 
cout << "Please enter the length in inches:\n"; 
cin >> inches; 


if (choice == 1) 
{ 
    feet = (inches/12); 
    cout << fixed << showpoint << setprecision(1); 
    cout << feet << " feet" << inches % 12 << " inches\n"; 
} 
else if (choice == 2) 
{ 
    yards = (inches/36); 
    cout << fixed << showpoint << setprecision(1); 
    cout << yards << " yards" << inches % 36 << " inches\n"; 
} 
else if (choice == 3) 
{ 
    centimeters = (inches/.39370); 
    cout << fixed << showpoint << setprecision(1); 
    locentimeters = (inches % centnum); 
    cout << centimeters << locentimeters << " centimeters\n"; 
} 
else if (choice == 4) 
{ 
    meters = (inches/39.370); 
    cout << fixed << showpoint << setprecision(1); 
    lometers = (inches % meternum); 
    cout << meters << lometers << " meters\n"; 
} 
else 
    cout << "That is an invalid entry.\n"; 
+0

什麼問題? – NobodyNada 2015-02-17 22:15:41

回答

1

問題:

操作%應具有整型。而centnum本身就是int。你.39370其轉化爲int初始化爲0。這就是爲什麼在菜單3您通過零得到一個鴻溝:

locentimeters = (inches % centnum); // diveide by 0 

而且meternum也是int。您將其初始化爲39.370,轉換爲int將爲39。這就是爲什麼在菜單4你inacurate resuts:

lometers = (inches % meternum); // meternum is 39 and not 39.370 

如果你定義常量爲雙不是int是不夠的:

  • %需要和整體式diviser。所以用double你將無法編譯。
  • fmod被定義爲來自積分商的餘數。

解決方案:

第一步是用正確的類型定義常量:

const double meternum = 39.370; 
const double centnum = .39370; 

然後,通過fmod()更換%。與此同時,如果您使用floor()作爲分部的組成部分,則fmod的結果將變得非常靈敏。就像這樣:

... 
else if (choice == 3) 
{ 
    centimeters = floor(inches/centnum); 
    cout << fixed << showpoint << setprecision(1); 
    locentimeters = fmod(inches,centnum); 
    cout << centimeters << locentimeters << " centimeters\n"; 
} 
else if (choice == 4) 
{ 
    meters = floor(inches/ meternum); 
    cout << fixed << showpoint << setprecision(1); 
    lometers = fmod(inches,meternum); 
    cout << meters << lometers << " meters\n"; 
} 
... 

小備註:一個好習慣是要麼使用與像3.370雙文字雙打或浮動文字使用花車就像3.370 ˚F。如果您將花車與雙層車混合使用,您可能會遇到細微的四捨五入問題。

相關問題