C++ noob question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

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; }

20th Oct 2018, 12:54 PM
Marius
5 Answers
+ 7
Variable 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;
20th Oct 2018, 12:58 PM
Hatsy Rei
Hatsy Rei - avatar
0
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;
20th Oct 2018, 1:10 PM
Marius
0
U need arrays
31st Dec 2018, 3:37 AM
William Tseng
William Tseng - avatar
0
#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.
31st Dec 2018, 3:38 AM
William Tseng
William Tseng - avatar
- 1
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
20th Oct 2018, 1:01 PM
Marius