Program

Jun 12, 2014 at 3:52pm
Hello!

I bought a C++ book and have started trying the example. Here is a code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}

int main()
{
     cout<< "Please enter a floating-point value:";
     double n;
     cin>>n;
     cout<< "n =="<<n
         << "\nn+1 =="<<n+1
         << "\nthree times n=="<<3*n
         << "\ntwice n=="<<n+n
         << "\nn squared=="<<n*n
         << "\nhalf of n=="<<n/2
         << "\nsquare root of n=="<<sqrt(n)
         << "\n";  // another name for newline ("end of line") in output

}



Now There is exercise:

Get this little program to run. Then, modify it to read an int rather than a double. Note that sqrt() is not defined for an int so assign n to a double and take sqrt() of that.

How should I do this? I get error message when trying do change the code.
Jun 12, 2014 at 4:05pm
You haven't showed us your modified code or the error message(s), so i'm not sure how anyone can help. Other than writing it for you.

edit: here you go.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

int main()
{
	std::cout<< "Please enter a integer value:";
	int n;
	std::cin>>n;

	double nAsDouble = static_cast<double>(n);

	std::cout<< "n =="<<n
		<< "\nn+1 =="<<n+1
		<< "\nthree times n=="<<3*n
		<< "\ntwice n=="<<n+n
		<< "\nn squared=="<<n*n
		<< "\nhalf of n=="<<n/2
		<< "\nsquare root of n=="<<sqrt(nAsDouble)
		<< "\n";  // another name for newline ("end of line") in output

	return 0;
}
Last edited on Jun 12, 2014 at 4:22pm
Jun 12, 2014 at 6:04pm
Ok thanks for your reply. In the part where you assign n to a double you write

double nAsDouble = static_cast<double>(n);

however I have never learned that one. Would it be possible to assign n to double just by writing

n=double ?
Last edited on Jun 12, 2014 at 6:05pm
Jun 12, 2014 at 6:05pm
If im not mistaken you are using bjatne strustrup book
Jun 12, 2014 at 7:12pm
Yes that`s true but how about my question?

Thank you for your interest.
Jun 12, 2014 at 7:42pm
closed account (j3Rz8vqX)
n=double is invalid: n being a variable and double being a data type.

Another solution would be cast n to double then assign it: double nAsDouble = (double) n;

or simply assign n to a double:
A double has more precision, it would do little harm, if any: double nAsDouble = n;.
Jun 13, 2014 at 7:29am
Another solution would be cast n to double then assign it: double nAsDouble = (double) n;


That's what i did in my code in my earlier post. i just used the safer c++ conventional cast.

OP, if you're using C++ and not C (which you are) i would stay away C-style casts that Dput is recommending.
Last edited on Jun 13, 2014 at 7:30am
Topic archived. No new replies allowed.