2014-04-05 95 views
0

我在這裏不知所措,所以我正在尋找任何提示以指引我朝着正確的方向前進。我不知道如何輸入我從華氏溫度轉換成攝氏溫度數組的攝氏度值。爲了這個目的,我嘗試在另一個for循環中工作,但它僅在第一個for循環的計算結果後輸出C的最後一個值。有任何想法嗎?提前致謝。在第一回路本身陣列中將數組中的數值放入另一個數組

// Temperature Converter 

#include <iostream> 
#include <iomanip> 

using std::cout; 
using std::endl; 
using std::setw; 

int main() 

double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 }; 
double centigrade[] = { 0 }, C(0); 
int i(0); 

cout << setw(13) << "Farenheit " << setw(9) << " Centigrade"; 
cout << endl; 

    for (double t : temps) 
    { 
     C = (t - 32) * 5/9; 
     cout << setw(10) << t << setw(12) << C; 
     cout << endl; 
    } 
    for (i = 0; i <= 12; i++) 
    { 
     centigrade[i] = C; 
     cout << centigrade[i] << endl; 
    } 
return 0; 
} 
+0

你的'攝氏溫度'數組太小。你應該爲它分配一大塊內存。 – merlin2011

+0

@ merlin2011太小了?那麼我應該把它改成'code'double centigrade [12]'code'? – user3465469

+0

'double centigrade [12]'*** – user3465469

回答

1

下面是根據對方的回答一個完整的工作示例。

#include <iostream> 

using std::cout; 
using std::endl; 

int main() { 

    double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 }; 
    const int count = sizeof(temps)/sizeof(temps[0]); 

    double centigrade[count]; 

    for (int i = 0; i < count; i++) { 
     centigrade[i] = (temps[i] - 32) * 5/9; 
     cout << centigrade[i] << endl; 
    } 
    return 0; 
} 

如果你想在不明確的索引循環工作,然後用std::vector<double> centigrade取代double centigrade[count];,並與更換循環:

for (double t : temps) 
    centigrade.push_back((t - 32) * 5/9); 

如果當時就想一個數組回來出於某種原因,你可以使用這個技巧得到一個數組:

double* array_version = &centigrade[0]; 
+0

@dyp,感謝您的建議和更新。 '-pedantic-errors'是一個有用的標誌,可以知道。 – merlin2011

+0

是否有無論如何你可以保持基於範圍的循環設置? – user3465469

+0

如果你指的是'for(double t:temps)',那麼你必須a)維護一個顯式索引,或者b)使用'std :: vector'而不是數組,然後使用'push_back()'來添加到它。 – merlin2011

0

商店值..

for (i=0;i<=12;i++) 
{ 
    centigrade[i]= (temps[i] - 32) * 5/9; 
    cout << setw(10) << temps[i] << setw(12) << centigrade[i]; 
    cout << endl; 
} 

U可以通過找到的臨時工大小陣列dynamically..maybe概括for循環

的sizeof(臨時工)/ 的sizeof(臨時工[0]);

同樣對於攝氏陣列相應地分配存儲器。

0

我添加了一個新的答案,基於澄清OP的問題,而不是更新我的存在g的答案,因爲我覺得上下文更清楚這種方式。

如果你想使用基於範圍的循環,避免std::vector,有辦法做到這一點,但這種解決方案更在C精神比C++,因爲它使用指針運算。

#include <iostream> 

using std::cout; 
using std::endl; 

int main() { 

    double temps[] = { 65.5, 68.0, 38.1, 75.0, 77.5, 76.4, 73.8, 80.1, 55.1, 32.3, 91.2, 55.0 }; 
    const int count = sizeof(temps)/sizeof(temps[0]); 

    double centigrade[count]; 
    double * walker = centigrade; 

    for (double t : temps) 
     *walker++ = (t - 32) * 5/9; 

    // verify results by printing.  
    for (double t: centigrade) 
     cout << t << endl; 


    return 0; 
} 
相關問題