2017-03-21 3 views
0

Der folgende Code hängt die Werte von y [i] in derselben Spalte an wie x [i], y [0], die unterhalb von x [10] beginnt. Ich möchte die Werte von y [i] in der zweiten Spalte neben der ersten Spalte der Werte von x [i] anfügen. Könnten Sie mir bitte helfen, wie das geht?Wie füge ich Daten in Spalten an?

#include <fstream> 
using namespace std; 
int main() { 
    ofstream outfile; 
    double x[10], y[10]; 
    for(int i=0; i<10; i++){ 
    x[i] = i+10; 
    } 
    for(int i=0; i<10; i++){ 
    y[i] = i-10; 
    } 
    outfile.open("result.txt", ios_base::app); 
    outfile << "loop: " << 1 << endl; 
    for(int i=0; i<10; i++){ 
    outfile << x[i] << "\n"; 
    } 
    outfile << "loop: " << 2 << endl; 
    for(int i=0; i<10; i++){ 
    outfile << y[i] << "\n"; 
    } 
    outfile.close(); 
return 0; 
} 
+0

Versuchen Sie, so etwas wie 'x [i + 1] = x zu tun [ i + 1] + y [i]; '? –

Antwort

0

ändern

outfile << "loop: " << 1 << endl; 
for(int i=0; i<10; i++){ 
    outfile << x[i] << "\n"; 
} 

To-

outfile << "loop: 1 \t loop: 2" << endl; 
for(int i=0; i<10; i++){ 
outfile << x[i] << " \t "<<y[i]<<"\n"; 
} 

Keine Notwendigkeit für

outfile << "loop: " << 2 << endl; 
    for(int i=0; i<10; i++){ 
    outfile << y[i] << "\n";} 
0

Versuchen Sie, dies zu tun?

#include <fstream> 
using namespace std; 
int main() { 
    ofstream outfile; 
    double x[10], y[10]; 
    for(int i=0; i<10; i++){ 
    x[i] = i+10; 
    y[i] = i-10; 
    } 

    outfile.open("result.txt", ios_base::app); 
    outfile << "loop: " << 1 << endl; 
    for(int i=0; i<10; i++){ 
     outfile << x[i] << ' ' << y[i] << "\n"; 
    } 
    outfile.close(); 
    return 0; 
} 
+0

Die ersten beiden for-Schleifen können für die Schleife auf eins reduziert werden. – Shiping

+0

Das funktioniert auch perfekt. Ich konnte deine Antwort nicht auffrischen, weil ich ein neues Mitglied in diesem Forum bin und nicht genug Reputation habe. Vielen Dank für deine Hilfe. – user3328741

+0

@ user3328741 es ist in Ordnung, solange Sie Ihre Antwort erhalten haben. – Shiping

Verwandte Themen