What\'s wrong with my code? I need to generate three random numbers from 1-100 a
ID: 3902063 • Letter: W
Question
What's wrong with my code? I need to generate three random numbers from 1-100 and calculate the avg. I don't see why my code is not working. Any help?
//Start of code
#include <iostream>
#include <stdlib.h> //for rand and srand
#include <ctime> // for time function
#include <iomanip> // for setprecision
#include <stdio.h> // for NULL
using namespace std;
int main()
{
// Variables
int y1; // To hold value #1
int y2; // To hold value #2
int y3; // To hold value #3
srand(time(NULL));
cout << "This program will pick three random numbers between 1 and 100, inclusive, ";
cout << "calculate their average, and then display the numbers and their average..." << endl;
{
y1 = rand() % 100 + 1;
y2 = rand() % 100 + 1;
y3 = rand() % 100 + 1;
cout << "Numbers: " << y1 << ", " << y2 << ", " << y3 << endl;
}
double y1, y2, y3, avg;
avg = y1 + y2 + y3 / 3;
cout << "Average: ";
cout << setprecision(2) << avg << endl;
return 0;
}
Explanation / Answer
Hey helo.
Your code is good..but only mistake I found is..you are trying to 're declare the variables int y1 , y2,y3 as double y1,y2,y3.
Only you need to declare double avg.the re declaration of the int variables to float is incorrect... remaining code is perfect.
So try removing that and execute.
================
#include <iostream>
#include <stdlib.h> //for rand and srand
#include <ctime> // for time function
#include <iomanip> // for setprecision
#include <stdio.h> // for NULL
using namespace std;
int main()
{
// Variables
int y1; // To hold value #1
int y2; // To hold value #2
int y3; // To hold value #3
srand(time(NULL));
cout << "This program will pick three random numbers between 1 and 100, inclusive, ";
cout << "calculate their average, and then display the numbers and their average..." << endl;
{
y1 = rand() % 100 + 1;
y2 = rand() % 100 + 1;
y3 = rand() % 100 + 1;
cout << "Numbers: " << y1 << ", " << y2 << ", " << y3 << endl;
}
// here remove the double declaration of variables y1 ,y2,y3
double avg;
avg = y1 + y2 + y3 / 3;
cout << "Average: ";
cout << setprecision(2) << avg << endl;
return 0;
}
==================
Hope this will help
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.