Reputation: 616
#include <iostream>
#include <string>
using namespace std;
int main() {
double age;
double months;
string name;
months = age*12.0;
cout << "Enter your name and age: ";
cin >> name >> age;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
return(0);
}
The program asks for name and age, and should out put the name and age in a sentence with the age in months in parentheses. Output gives something like: Hello Bob age 20 (1.82561e-313 months), but should be Hello Bob age 20 (240 months). I did not use int because I wanted to be able to input non int values for age. I have tried 12 instead of 12.0 and tried declaring a variable and doing months = age*m where m = 12.0 but is result is the same. By the way, the random value is about the same regardless of what variable age is. Why is this happening? Also, would this be a link-time error or run-time error?
Upvotes: 2
Views: 1251
Reputation: 125651
You're doing the multiplication using age
before it's initialized. What value would you expect it to give you?
Change your code to first get the age, and then do the multiplication:
cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
Upvotes: 4
Reputation: 300499
Move the calculation of months
to after the point age is entered (age
was uninitialised in the original code):
cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
Upvotes: 2