2017-08-27 76 views
-4

I的值具有下面的代碼商店COUT

#include <iostream> 
#include <math.h> 
#include <string> 
#include <sstream> 
using namespace std; 
int main() { 
int value 
cout << "Input your number: " << endl; 
cin >> value; 
string s = to_string(value); 
const int count = s.length(); 
int position = count; 
for (int i = 1; i < count + 1; i++) 
{ 
    int pwr = pow(10, position - 1); 
    cout << ((value/pwr) + position) % 10; 
    position--; 
    value = value % pwr; 
} 

相反COUT的,我怎樣才能使用for循環的((value/pwr) + position) % 10值存儲到一個變量。非常感謝你的幫助。

[編輯] 我增加了一個陣列,而不是

int val[7]; 
int position = count; 
for (int i = 1; i < count + 1; i++) 
{ 
    int pwr = pow(10, position - 1); 
    val[i-1] = ((value/pwr) + position) % 10; 
    position--; 
    value = value % pwr; 
} 
cout << "Encoded value is: "; 
for (int i = 0; i < 8; i++) 
{ 
    cout << val[i]; 
} 

它能夠輸出I想要的值,但有一個運行時故障#2 - 疊圍繞變量「VAL」被損壞。這是爲什麼?

+0

剛剛創建矢量和推回你的結果 –

+0

不能使用代碼,我們還沒有在 –

+0

類學習@永亨邱。 http://en.cppreference.com/w/cpp/container/vector –

回答

0

您可以使用像矢量一樣的STL容器。

#include <iostream> 
#include <math.h> 
#include <string> 
#include <sstream> 
#include <vector> 

using namespace std; 
int main() { 
    int value; 
    cout << "Input your number: " << endl; 
    cin >> value; 
    string s = to_string(value); 
    const int count = s.length(); 
    int position = count; 

    vector<int> outputs; 

    for (int i = 1; i < count + 1; i++) 
    { 
    int pwr = pow(10, position - 1); 
    outputs.push_back(((value/pwr) + position) % 10); 
    cout << outputs.back(); 

    position--; 
    value = value % pwr; 
    } 

    cout << endl; 

    // iterate through the vector later 
    for (auto i : outputs) 
    { 
    cout << i; 
    } 

    cin.get(); 
} 
+0

感謝您的支持,但不能使用我們在課堂上沒有學過的代碼。 –

0

商店載體,然後打印

它不是那麼難。至於你不知道會有怎樣的規模或如何結果數多將在那裏它是使用矢量有用。

此處參考http://en.cppreference.com/w/cpp/container/vector

#include <iostream> 
#include <math.h> 
#include <string> 
#include <sstream> 
#include<vector> 
#include<iterator> 
#include<algorithm> 

using namespace std; 

int main() { 
    int value; 
    vector<int> results; 
    cout << "Input your number: " << endl; 
    cin >> value; 
    string s = to_string(value); 
    const int count = s.length(); 
    int position = count; 
    for (int i = 1; i < count + 1; i++) 
    { 
     int pwr = pow(10, position - 1); 
     auto val = ((value/pwr) + position) % 10; 
     results.push_back(val); 
     position--; 
     value = value % pwr; 
    } 
    copy(results.begin(),results.end(),ostream_iterator<int>(cout," ")); 

} 

輸出

Input your number: 
12 
3 3 Program ended with exit code: 0