Problem with floating variables

Pages: 12
Nov 16, 2019 at 5:31pm
How to display the decimal of floating variables?
This program is to examine the prim number and quotient but the z variable doesn't output fraction.. why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  #include<iostream>
#include<process.h>
using namespace std;

int main()
{
 char again;
 do
 {
	
	int x;
label:	cout<<"please enter number"<<endl;
	    cin>>x;

	while (x<=2)
	{
		cout<<"Please enter number more than 2"<<endl;
		cin>>x;
	}

	float z;
	

	for(int i=x-1;i>=2;i--)

	{
	
		z = x % i;

		if(z==0)
		{
			cout<<x<<"/"<<i<<"="<<z<<endl;
			cout<<"this number "<<x<<"is not a primary number"<<endl;
			cout<<"try another number?"<<" press 'y' for yes"<<endl;
			cin>> again;
			if(again=='y')
			{
				goto label;
			}
			else
			{
			exit (0);
			}
		}

		z=x/i;  
	    cout<<x <<"/"<<i <<"= "<<z<<endl;  //why the output of z not fractional whilest it is declared as float?
	}

	cout<<"this number "<<x<<" is a primary number"<<endl;

		cout<<"try another number?"<<" press 'y' for yes"<<endl;
		
		cin>>again;

 }while (again=='y');
 
return(0);
}

Nov 16, 2019 at 5:54pm
In C++, an int divided by an int gives you an int.

What is 3/2?
It is 1.
It is NOT 1.5

What is 8/3?
It is 2.
It is NOT 2.66666667

In your code, x is an int.
In you code, i is an int.

In your code, x/i is an int divided by an int, so it gives you an int.
Nov 16, 2019 at 5:59pm
So I have to declare all vars. As float to get a float output ?
Nov 16, 2019 at 6:10pm
That would do it.

Alternatively, you could cast them to float at the point you do the division. Something like:

z = static_cast<float>(x) / i;
Nov 16, 2019 at 6:16pm
Thanks bro, I ll try it
Nov 16, 2019 at 6:21pm
Hello semsemdiver,

First off "double" is the preferred choice for floating point numbers.

Avoid using the "goto" that is what you have the do/while loop for.

The line z = x % i; returns an "int" and stores it in a "double", so it will always be ".0000000".

On the other hand z=x/i; is more likely to return a decimal value other than (0) zero, except that you are doing integer division, so the decimal part will always be ".000000".

To print the zeros for a "double" add the header file "<iomanip>" and put this line:
std::cout << std::fixed << std::showpoint << std::setprecision(2);
above the "do" of the do/while loop. "std::noshowpoint" is the default value, so if the "double" ends with ".0" it will not print.

In this bit of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (z == 0)
{
	cout << x << "/" << i << " = " << z << endl;

	cout << "this number " << x << "is not a primary number" << endl;

	cout << "try another number?" << " press 'y' for yes" << endl;
	cin >> again;

	//if (!(again == 'y' || again =='Y'))  // <--- Check for both cases.
	if (std::tolower(again) == 'y')  // <--- Include header file "<cctype>".
	{
		goto label;
	}
	else
	{
		exit(0);
	}
}

Avoid using the "goto". You need a way to get tot he end of the do/while loop. Actually this if statement should not be here. You should be using the one at the bottom of the loop.

Since you are in "main" "return 0;" is a better choice, but should not be here.

The program still needs some changes to work properly.

Hope that helps,

Andy
Nov 16, 2019 at 7:52pm
thanks a lot Andy for your reply, i appreciate your help
actually i have just started learning C++ and i have a small background of programming in visual basic 6 , it was a bout 10 years ago, so i still exploring the language but i think it much more harder than v.b as i wasn't professional in v.b too, so excuse me if i made some unorganized program.

anyway why avoid goto it is a piece from the language it should has a function or task to do,
most people advice to avoid it i don't know why?

Thanks again Andy :)
Nov 17, 2019 at 11:58am
Hello semsemdiver,

No worries. You have to start somewhere. Sometimes it is the little things that you do not realize or understand.

Andy
Nov 17, 2019 at 1:05pm
anyway why avoid goto it is a piece from the language it should has a function or task to do,
most people advice to avoid it i don't know why?


Essentially, because the use of it makes it much more likely that you will create "spaghetti code". Code that jumps about from place to place, making it difficult to follow and difficult to debug and difficult to understand and difficult to maintain.

When you see a piece of code with a label in it, all you know is that piece of code could start executing at any time, from anywhere. If you're in that piece of code, you don't know how you got there; a goto, or just normal flow? If a goto, which goto? If the goto meant that lots of lines were jumped over, lines containing variables and initialisations and value setting, what happens to them? The variable exist, but did they get initialised?

Basically, with just a few goto in the code, you can make an enormous unmaintainable unfixable mess that nobody understands. It breaks modularity, breaks function flow, breaks control loops, renders useless any understanding people have about the program structure because the code can just jump around.

There *are* circumstances in which it makes sense. In which careful use of goto enhances the code and makes it simpler and safer (although mostly in C code; C++ doesn't suffer from some of the things that made it helpful in C). This situation ,where you're using it instead of a loop, isn't one of them.
Last edited on Nov 17, 2019 at 1:06pm
Nov 17, 2019 at 1:12pm
Hi repeater
Thanks a lot .. understood
Nov 17, 2019 at 1:17pm
Hi Andy
That is the problem, I don't know how and where to start, I love programming
and solving problems but I don't have time to attend course as I work offshore, so I have to self study, I want to work in something I love like programmer or software engineer but I don't know how to start and what is the most direct and affective way to start with
Any advice it would be appreciated.
Thanks again
Semsemdiver
Nov 17, 2019 at 1:56pm
Hello semsemdiver,

Been there, done that.

I started with C many years ago. All the books I read I could follow until they started in to classes. Then I found https://www.learncpp.com/ which explains everything in simple terms that are easier to understand. And it looks to me that is is well updated.

At the bottom of most pages there are exercises that cover what you just read
and beyond that there are questions and answers that help.

Andy
Nov 17, 2019 at 2:29pm
HI Andy

Thanks i'll try it.
semsemdiver
Nov 17, 2019 at 2:29pm
@maniaqq247,

Most times it is not nice to invade someone else's thread. Most times it is better to start your own thread.

You say the you do not understand. Understand what exactly. Hard to answer your statement is one does not know what the question is.

Andy

Edit:

Looks like it was withdrawn.
Last edited on Nov 17, 2019 at 2:30pm
Nov 17, 2019 at 2:39pm
Here is a modified version of your program that doesn't use goto and is (I think) better structured. Notice that it's divided into clear sections:
1. The outer loop
2. Get the number to check
3. Determine if it's prime while printing the quotient along the way
4. Printing whether it's prime
5. Asking if the user wants to check another number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<iostream>
#include<process.h>
using namespace std;

int
main()
{
    char again;
    do {
	int x;

	// Loop to get the number. Note that this loop exits
	// in the MIDDLE of the loop. Don't be afraid to do this.
	// Sometimes it makes the most sense.
	while (true) {
	    cout << "please enter number" << endl;
	    cin >> x;
	    if (x>2) break;	// break out of loop in the middle

	    // If you get here, the number is bad
	    cout << "The number must be more than 2" << endl;
	}

	// Figure out if the number is prime
	bool isPrime = true;
	for (int i = x - 1; i >= 2; i--) {
	    cout << x << "/" << i << "= " << (double)x/i << endl;
	    if (x % i == 0) {
		isPrime = false;
		break;
	    }
	}

	// Now that you know whether it's prime, print the result
	if (isPrime) {
	    cout << "this number " << x << " is a primary number" << endl;
	} else {
	    cout << "this number " << x << "is not a primary number" << endl;
	}

	// Ask if they want to check another number
	cout << "try another number?" << " press 'y' for yes" << endl;
	cin >> again;
    } while (again == 'y');

    return (0);
}

Nov 17, 2019 at 2:51pm
hi dhayden

thank you, looks brilliant although it is a new technique to me but i will figure it out
i saw your profile, you are very professional, would you please advice me how to be a good programmer, software engineer :)

i appreciate your help

best regards

semsemdiver
Last edited on Nov 17, 2019 at 2:54pm
Nov 17, 2019 at 3:11pm
Hello semsemdiver,

As you have understood dhayden's example I did come up with this. It is not the best, but does clean up what you started with and still could use some improvement.

Note the comments in the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <cctype>
#include<iostream>
#include <iomanip>
//#include<process.h> // <--- Not needed or used in the program.

//using namespace std;  // <--- Best not to use.
// A recent post that is worth reading. http://www.cplusplus.com/forum/beginner/258335/

/*
// An alternative to using namespace std;
using std::cin;
using std::cout;
using std::endl;
*/

int main()
{
	char again;

	std::cout << std::fixed << std::showpoint << std::setprecision(2); // <--- Only needs done once. Needs header file "<iomanip>".

	do
	{
		int x;
		double z;

		std::cout << "\n Please enter number: ";  // <--- Changed. Added ':' and space at the end and removed the "endl". This puts the "cin" on the same line.
		std::cin >> x;

		while (x <= 2)
		{
			std::cout << "\n    Please enter number more than 2: ";
			std::cin >> x;
		}

		for (int i = x - 1; i >= 2; i--)
		{
			z = x % i;

			if (z == 0.0)  // <--- Changed. 0 may work, but 0.0 is more proper since "z" is defined as a double.
			{
				std::cout << "\n " << x << "/" << i << " = " << z/* << endl*/;  // <--- Changed.

				std::cout << "\n\n this number " << x << " is not a primary number" << std::endl;
				  // <--- Changed.

				break; // <--- Eliminates the need for the "goto". Also the do/while loop is all you need to work with.
			}

			// <--- Without the type cast this is integer division, so the decimal value will always be (0) zero.
			// <--- BTW "i" will be promoted to a "double" at compile time.
			z = static_cast<double>(x) / i; // <--- From Repeater's suggestion.

			std::cout << "\n " << x << "/" << i << " = " << z;  //why the output of z not fractional whilest it is declared as float?
		}

		if (z != 0.0) // <--- Used this, but could be done differently. Just did not work on it yet.
		{
			std::cout << "\n\n this number " << x << " is a primary number" << std::endl;
		}

		std::cout << "\n try another number? " << " press 'y' for yes: "; // <--- This is the only one you need.
		std::cin >> again;

	} while (std::tolower(again) == 'y'); // <--- Or while (again == 'y' || again == 'Y'); to catch either case.

	return 0; // <--- The () are not needed, but makes no difference if you use them.
}


Hope that helps your understanding,

Andy
Nov 17, 2019 at 3:20pm
HI Andy

Thank you for your help.

why don't you use namespace std; instead of typing std:: many times in your code?
i just want to know your point of view?
the code has error when i built it ?!!

thanks a lot

best regards.

semsemdiver
Last edited on Nov 17, 2019 at 3:23pm
Nov 17, 2019 at 4:36pm
If you put using namespace std; in your code, then you automatically drag in every class and function in the std namespace that are in the headers you've included. There could be hundreds. Thousands. They have simple, obvious names that you might use yourself. max. min. swap. Many many more.

Basically, it's just asking for trouble. It's asking to drag in hundreds or thousands of functions and classes that you might accidentally collide with, without even realising.

If you put using namespace std; in a header file that someone else might #include , when they find out what your header file did to their code, they will take you out to the carpark to express their displeasure :)
Last edited on Nov 17, 2019 at 4:37pm
Nov 17, 2019 at 4:40pm
Hello semsemdiver,

Back when I first started here "using namespace std:" was frowned upon and many people were saying not to use it. Also putting things like "#include <iostrean>" and others in a header is wrong.

At some time this appears to have changed and I missed it. It seems now that putting header files in a header file that you write is OK if needed. And that using the line "using namespace std;" is being used by some of the same people that use to say not to.

Based on what I was reading, and even though I did not fully understand it back then, I started qualifying everything with "std::" and started to learn what was in the standard name space.

If you are not familiar with name spaces these should help.

http://www.cplusplus.com/doc/tutorial/namespaces/
https://www.learncpp.com/cpp-tutorial/4-3b-namespaces/

After about a week and a half I used it without thinking about it. The link provided should help you to understand. If not try a search. I think "using namespace std" should work. There are many other posts on this topic.

I have also come to accept that some people pay a lot of money to take a class and to be taught the wrong way to code and think it is the only way to code.

Using namespace standard in the global scope of the file WILL get you in trouble some day.

In your early days in school you were taught that 1 + 1 = 2. Do you need examples to prove this every time you see it or do you just accept that it is a fact.

When it comes to using "std::" I accept this as a fact and realized that it will become more clear in the future.

When you start programming what you are likely to use first is "std::cin", "std::cout", "std::endl" and "std::string" with "std::vector" maybe coming next. As you include more header files there is more that is put in the standard namespace and more that you will need to learn how to qualify.

The question comes do you want to learn a little bit at a time or everything all at once?

There is also the possibility that when you are hired by a software company you could be told the "using namespace std;" will never be allowed in a program. Now do you want to learn everything that is in the standard namespace at one time? Just saying.

You said:
the code has error when i built it ?!!
What error? Where? Be more specific and include the error message as the compiler gave it to you.

In VS 2017 the program compiles with no errors or warnings, so I have no idea what your problem is. Also I do not believe I know what IDE/ compiler you are using and on what operating system. This helps.

Hope that helps,

Andy
Pages: 12