Program

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.
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
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
If im not mistaken you are using bjatne strustrup book
Yes that`s true but how about my question?

Thank you for your interest.
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;.
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
Topic archived. No new replies allowed.