C++ noob question
Hi, I am new to codding, and trying to learn step by step. Can someone please tell me why is the bellow code wrong? It is supposed to store some weights and distances #include <iostream> using namespace std; int main() { int i, n, g,d, m, s, p; cout<<"nr destinatii= "; cin>>n; for (i=0; i<n; i++) { cout<<"greutate= ";cin>>g[i]; cout<<"distanta= ";cin>>d[i]; } return 0; }
10/20/2018 12:54:21 PM
Marius
5 Answers
New AnswerVariable g and d were not declared as arrays. Instead do: int n; cin >> n; // dynamically allocate n blocks of memory of type int to g and d int* g = new int[n]; int* d = new int[n]; for (int i = 0; i < n; i++) { cin >> g[i] >> d[i]; } // more stuff here // free your dynamically allocated memory delete [] g; delete [] d;
nevermind, i think i got it. int i, n, m, s, p; double g,d; cout<<"nr destinatii= "; cin>>n; for (i=0; i<n; i++) { cout<<"greutate= ";cin>>g; cout<<"distanta= ";cin>>d; s=s+g*d; p=p+d;
#include <iostream> using namespace std; int main() { int i, n,m, s, p; cout<<"nr destinatii= "; cin>>n; int d[n],g[n]; for (i=0; i<n; i++) { cout<<"greutate= ";cin>>g[i]; cout<<"distanta= ";cin>>d[i]; } //The calculation goes here return 0; } It's quite fine for basic coding.
but g and d are integers, i need g to store the weights and d the distances I want to store n distances and n weights, and then calculate the weighted average to weight