+ 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; }
5 Antworten
+ 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;
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;
0
U need arrays
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.
- 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