2015-04-29 27 views
-3

基本上我的問題是我在循環外部創建了一個變量(字符串),我想在循環中使用它。下面是一個示例代碼,試圖更好地解釋:我不知道如何引用循環外的變量(C++)

int myage = 0; // set by user 
int currentyear = 2015; 

cout << "How old are you?" << endl; 
cin >> myage; 

for(int i=0; i>98; i++) { 
    myage=myage+1; 
    currentyear=currentyear+1; 

    cout << "In " << currentyear << " you will be " << myage << " years old." << endl; 
} 

這只是我做了嘗試,以便更好地解釋一個簡單的例子,所以我的問題是:有沒有什麼辦法,我可以使用myagecurrentyear變量在這個循環中?如果是,如何?

不要猶豫,問你是否需要更多信息或具體數據。

+0

你是說你不能在循環內使用'myage'變量嗎? – Cristik

+0

如果你不能使用它們,你會得到一個編譯器錯誤。 – chris

+0

@chris:讓我們不要跳入苛刻的結論,也許他正在使用一個更新的編譯器:) – Cristik

回答

6

的循環永遠不會執行

for(int i=0; i>98; i++){ 

因爲i>98false

+0

謝謝你讓我知道,但我很快就寫下了這個例子,試圖更好地解釋我的問題。 – Natex

+1

令人沮喪的是,OP改變了這個答案已經過時的問題。 –

+0

我不應該改變它嗎? – Natex

0

如果你問我想你問的,絕對。 for循環幾乎更像是一種便利的語法,爲您提供了指定初始條件,中斷條件和執行每次迭代的命令的位置。據我所知,你可以使用盡可能多或儘可能少的這些,只要你想,例如

#include <iostream> 
int main(){ 
    int myage = 0; 
    for(; myage<10; myage++) 
     std::cout << myage << std::endl; 
} 

將通過9

+0

好的信息!我會記住的,謝謝! – Natex

0

打印出數字0由於這已經回答了,你可以改進和使用+ =運算符這樣縮短代碼: myage += 1;

或本: myage++;

,而不是myage=myage+1;

0

瞭解範圍很重要。循環和函數創建一個範圍,並且它們總是可以在更高的範圍訪問事物;然而,事情不能從更小的範圍訪問。對象在其作用域的整個期間都存在,並且該作用域內的任何對象都可以訪問它們。

// Global scope: 
int g = 0; // everything in this file can access this variable 

class SomeClass 
{ 
    // Class scope 
    int c = 0; 
    void ClassFunction() 
    { 
     // ClassFunction scope 
     // Here we can access anything at global scope as well as anything within this class's scope: 
     int f = 0; 

     std::cout << g << std::endl; // fine, can access global scope 
     std::cout << c << std::endl; // fine, can access class scope 
     std::cout << f << std::endl; // fine, can access local scope 
    } 
    // Outside of ClassFunction, we can no longer access the variable f 
}; 

void NonClassFunction() 
{ 
    // NonClassFunction scope 
    // We can access the global scope, but not class scope 
    std::cout << g << std::endl; 

    int n1 = 0; 
    for (...) 
    { 
     // New scope 
     // Here we can still access g and n1 
     n1 = g; 
     int x = 0; 
    } 
    // We can no longer access x, as the scope of x no longer exists 

    if (...) 
    { 
     // New scope 
     int x = 0; // fine, x has not been declared at this scope 
     { 
      // New scope 
      x = 1; 
      g = 1; 
      n1 = 1; 
      int n2 = 0; 
     } 
     // n2 no longer exists 
     int n2 = 3; // fine, we are creating a new variable called n2 
    } 
} 

希望這有助於向你解釋範圍。考慮到所有這些新信息,答案是肯定的:您可以在for循環中訪問您的變量,因爲這些變量的範圍在內部範圍內保持不變。

+0

非常有幫助,因爲我正在學習代碼。感謝您分享這一點! – Natex

相關問題