Monthly Archives: May 2012
C++ || Convert Time From Seconds Into Hours, Min, Sec Format
Here is another simple programming assignment. This page will demonstrate how to convert time from -seconds- into HH::MM::SS (hours, minutes seconds) format. So for example, if you had an input time of 9630 seconds, the program would display the converted time of 2 hours, 40 minutes, and 30 seconds.
Using simple math, this program utilizes the modulus operator, and the division operator during the conversion process.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Modulus - What is it?
How Many Seconds Are In One Hour?
How Many Seconds Are In One Minute?
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 30, 2012 // Taken From: http://programmingnotes.org/ // File: Convert-Time.cpp // Description: Demonstrates how to convert time from -seconds- into // HH::MM::SS (hours, minutes, seconds) format // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compiled five separate times to display different output)
====== RUN 1 ======
Enter a time in seconds: 9630
The time in HH:MM:SS format is: 2 hours, 40 minutes, and 30 seconds!
====== RUN 2 ======
Enter a time in seconds: 7200
The time in HH:MM:SS format is: 2 hours, 0 minutes, and 0 seconds!
====== RUN 3 ======
Enter a time in seconds: 45
The time in HH:MM:SS format is: 0 hours, 0 minutes, and 45 seconds!
====== RUN 4 ======
Enter a time in seconds: 134
The time in HH:MM:SS format is: 0 hours, 2 minutes, and 14 seconds!
====== RUN 5 ======
Enter a time in seconds: 31536000
The time in HH:MM:SS format is: 8760 hours, 0 minutes, and 0 seconds!
C++ || Char Array – Determine If A String Is A Number Or Not
The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using and manipulating character arrays.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Character Arrays
Cin.getline
Strlen - Get The Length Of A Char Array
Isalpha
Isspace
This program first prompts the user to input a line of text. After it obtains data from the user, using a for loop, it then displays the the string to the screen one letter (char) at a time. If the current character at that specific array index is a letter, a “flag” is set, indicating that the current word which is being displayed is not a number. If the “flag” is not set, the current word is indeed a number.
This program has the ability to intake multiple words at a time, so for example, if the user input was “Hello World 2012” the program would display the output:
Hello is NOT a number!
World is NOT a number!
2012 is a 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 24, 2012 // Taken From: http://programmingnotes.org/ // File: isNumber.cpp // Description: Demonstrates checking if a char array is a number // ============================================================================ #include <iostream> #include <cstring> #include <cctype> using namespace std; // function prototype void IsArryANum(char arry[]); int main() { // declare & initialize variables char arry[256]; // obtain data from user cout << "Enter some text to see if its a number or not: "; cin.getline(arry, sizeof(arry)); // getting line cout<<endl; IsArryANum(arry); return 0; }// end of main void IsArryANum(char arry[]) { int notANumber = 0; int length = strlen(arry); // get the length of the char array // and place a [space] at the end of it. Then // set the array index after the [space] to NULL arry[length] = ' '; arry[length + 1] = '\0'; // increment the length to account for the space we just added ++length; for(int x = 0; x < length; ++x) { cout <<arry[x]; // display the char at the current index // if the current char isnt a number, increment counter if(isalpha(arry[x])) { ++notANumber; } // if curerent char is a space, that indicates we are // at the end of the current word, so we // display the results to the user else if(isspace(arry[x])) { if (notANumber > 0) { cout <<"is NOT a number!" <<" There are "<<notANumber<<" letters" <<" in that word...\n"; } else { cout <<"is a number..\n"; } notANumber = 0; } } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compiled three separate times to display different output)
====== RUN 1 ======
Enter some text to see if its a number or not: My Programming Notes
My is NOT a number! There are 2 letters in that word...
Programming is NOT a number! There are 11 letters in that word...
Notes is NOT a number! There are 5 letters in that word...====== RUN 2 ======
Enter some text to see if its a number or not: May 30th 2012
May is NOT a number! There are 3 letters in that word...
30th is NOT a number! There are 2 letters in that word...
2012 is a number..====== RUN 3 ======
Enter some text to see if its a number or not: 5 31 2012
5 is a number..
31 is a number..
2012 is a number..
C++ || Snippet – Doubly Linked List Custom Template Queue Sample Code
This page will consist of sample code for a custom doubly linked list template queue. This implementation is considered a doubly linked list because it uses two nodes to store data in the queue – a ‘front’ and a ‘rear’ node. This is not a circular linked list, nor does it link forwards and/or backwards.
Looking for sample code for a stack? Click here.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Structs
Classes
Template Classes - What Are They?
Queue - What is it?
FIFO - First In First Out
#include < queue>
Linked Lists - How To Use
This template class is a custom duplication of the Standard Template Library (STL) queue class. Whether you like building your own data structures, you simply do not like to use any inbuilt functions, opting to build everything yourself, or your homework requires you make your own data structure, this sample code is really useful. I feel its beneficial building functions such as this, that way you better understand the behind the scene processes.
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
// ============================================================================ // Author: K Perkins // Date: May 20, 2012 // Taken From: http://programmingnotes.org/ // File: DoubleQueue.h // Description: This is a class which implements various functions // demonstrating the use of a queue. // ============================================================================ #include <iostream> template <class ItemType> class DoubleQueue { public: DoubleQueue(); /* Function: Constructor initializes queue Precondition: None Postcondition: Defines private variables */ bool IsEmpty(); /* Function: Determines whether queue is empty Precondition: Queue has been created Postcondition: The function = true if the queue is empty and the function = false if queue is not empty */ bool IsFull(); /* Function: Determines whether queue is full Precondition: Queue has been created Postcondition: The function = true if the queue is full and the function = false if queue is not full */ void EnQueue(ItemType item); /* Function: Adds new item to the back of the queue Precondition: Queue has been created and is not full Postcondition: Item is in the queue */ ItemType DeQueue(); /* Function: Returns and then deletes the first item in the queue Precondition: Queue has been created and is not empty Postcondition: The first item in the queue has been removed and the queue order is maintained */ ItemType Front(); /* Function: Returns (but does not delete) the first item in the queue Precondition: Queue has been created and is not empty Postcondition: The first item in the queue has been returned and the queue order is maintained */ ItemType Rear(); /* Function: Returns (but does not delete) the last item in the queue Precondition: Queue has been created and is not empty Postcondition: The last item in the queue has been returned and the queue order is maintained */ int Size(); /* Function: Return the current size of the queue Precondition: Queue has been initialized Postcondition: The size of the queue is returned */ void MakeEmpty(); /* Function: Initializes queue to an empty state Precondition: Queue has been created Postcondition: Queue no longer exists */ ~DoubleQueue(); /* Function: Removes the queue Precondition: Queue has been declared Postcondition: Queue no longer exists */ private: struct NodeType { ItemType currentItem; NodeType* next; }; NodeType* front; // front of queue NodeType* rear; // back of queue int size; }; //========================= Implementation ================================// template<class ItemType> DoubleQueue<ItemType>::DoubleQueue() { front = NULL; rear = NULL; size = 0; }/* end of DoubleQueue */ template<class ItemType> bool DoubleQueue<ItemType>::IsEmpty() { return (front == NULL); }/* end of IsEmpty */ template<class ItemType> bool DoubleQueue<ItemType>::IsFull() { try { NodeType* location = new NodeType; delete location; return false; } catch(std::bad_alloc&) { return true; } }/* end of IsFull */ template<class ItemType> void DoubleQueue<ItemType>::EnQueue(ItemType newItem) { if(IsFull()) { std::cout<<"nQUEUE FULLn"; } else { NodeType* newNode = new NodeType; // adds new node newNode-> currentItem = newItem; newNode-> next = NULL; if(rear == NULL) { front = newNode; } else { rear-> next = newNode; } rear = newNode; ++size; } }/* end of EnQueue */ template<class ItemType> ItemType DoubleQueue<ItemType>::DeQueue() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { NodeType* tempPtr = front; // temporary pointer ItemType item = front-> currentItem; front = front-> next; if(front == NULL) { rear = NULL; } delete tempPtr; --size; return item; } }/* end of DeQueue */ template<class ItemType> ItemType DoubleQueue<ItemType>::Front() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return front-> currentItem; } }/* end of Front */ template<class ItemType> ItemType DoubleQueue<ItemType>::Rear() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } else { return rear-> currentItem; } }/* end of Rear */ template<class ItemType> int DoubleQueue<ItemType>::Size() { if(IsEmpty()) { std::cout<<"nQUEUE EMPTYn"; } return size; }/* end of Size */ template<class ItemType> void DoubleQueue<ItemType>::MakeEmpty() { if(!IsEmpty()) { std::cout << "Destroying nodes ...n"; while(!IsEmpty()) { NodeType* tempPtr = front; //std::cout << tempPtr-> currentItem << 'n'; front = front-> next; delete tempPtr; } rear = NULL; size = 0; } }/* end of MakeEmpty */ template<class ItemType> DoubleQueue<ItemType>::~DoubleQueue() { MakeEmpty(); }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
===== DEMONSTRATION HOW TO USE =====
Use of the above template class is the same as its STL counterpart. Here is a sample program demonstrating its use.
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 |
#include <iostream> #include "DoubleQueue.h" using namespace std; int main() { // declare variables DoubleQueue<char> charQueue; DoubleQueue<int> intQueue; DoubleQueue<float> floatQueue; // ------ Char Example ------// char charArry[]="My Programming Notes Helped Me Succeed!"; int counter=0; while(charArry[counter]!='\0') { charQueue.EnQueue(charArry[counter]); ++counter; } cout<<"charQueue has "<<charQueue.Size()<<" items in it " <<"and contains the text:n"; while(!charQueue.IsEmpty()) { cout<<charQueue.DeQueue(); } cout<<endl; // ------ Int Example ------// int intArry[]={1,22,3,46,5,66,7,8,1987}; counter=0; while(counter<9) { intQueue.EnQueue(intArry[counter]); ++counter; } cout<<"nintQueue has "<<intQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; counter=0; while(!intQueue.IsEmpty()) { counter-=intQueue.DeQueue(); } cout<<counter<<endl; // ------ Float Example ------// float floatArry[]={41.6,2.8,43.9,4.4,19.87,6.23,7.787,68.99,9.6,81.540}; float sum=0; counter=0; while(counter<10) { floatQueue.EnQueue(floatArry[counter]); ++counter; } cout<<"nfloatQueue has "<<floatQueue.Size()<<" items in it.n" <<"The sum of the numbers in the queue is: "; while(!floatQueue.IsEmpty()) { sum-=floatQueue.DeQueue(); } cout<<sum<<endl; return 0; }// http://programmingnotes.org/ |
Once compiled, you should get this as your output
charQueue has 39 items in it and contains the text:
My Programming Notes Helped Me Succeed!intQueue has 9 items in it.
The sum of the numbers in the queue is: -2145floatQueue has 10 items in it.
The sum of the numbers in the queue is: -286.717
C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed
Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:
(1) Stack Based Infix To Postfix Conversion (Single Digit)
(2) Stack Based Postfix Evaluation (Single Digit)
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Stack Data Structure
Cin.getline
#include "ClassStackListType.h"
A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.
1 2 3 4 5 6 |
Well-Formed Expressions | Ill-Formed Expressions ------------------------------------|-------------------------------------- ( a b c [ ] ) | ( a b c [ ) ( ) [ ] { } | ( ( { ( a b c d e ) ( ) } | [ a b c d e ) ( ) } ( a + [ b - c ] / d ) | ( a + [ b - c } / d ) |
Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:
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 |
// An algorithm for a Well Formed expression Set 'balanced' to true Set 'symbol' to the first character in the current expression while(there are more characters AND 'balanced' == true) { if('symbol' is an opening symbol) { Push 'symbol' onto the stack } else if('symbol' is a closing symbol) { if the stack is empty 'balanced' = false else Set the 'openSymbol' to the item at the top of the stack Pop the stack Check to see if 'symbol' matches 'openSymbol' (i.e - if openSymbol == '(' and symbol == ')' then 'balanced' = true) } Set 'symbol' to the next character in the current expression } if('balanced' == true AND stack is empty) { Expression is well formed } else { Expression is NOT well formed }// http://programmingnotes.org/ |
======= WELL-FORMED EXPRESSIONS =======
This program uses a custom template.h class. To obtain the code for that class, click here.
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2012 // Taken From: http://programmingnotes.org/ // File: wellFormed.cpp // Description: Demonstrates how to check if an expression is well formed // ============================================================================ #include <iostream> #include "ClassStackListType.h" using namespace std; // function prototypes bool IsOpen(char symbol); bool IsClosed(char symbol); bool IsWellFormed(char openSymbol, char closeSymbol); int main() { // declare variables char expression[120]; char openSymbol; int index=0; bool balanced = true; StackListType<char> stack; // this is the stack declaration // obtain data from the user using a char array cout <<"Enter an expression and press ENTER. "<<endl; cin.getline(expression,sizeof(expression)); cout << "\nThe expression: " << expression; // loop thru the char array until we reach the 'NULL' character // and while 'balanced' == true while (expression[index]!='\0' && balanced) { // if input is an "open bracket" push onto stack // else, process info if (IsOpen(expression[index])) { stack.Push(expression[index]); } else if (IsClosed(expression[index])) { if(stack.IsEmpty()) { balanced = false; } else { openSymbol = stack.Top(); stack.Pop(); balanced = IsWellFormed(openSymbol, expression[index]); } } ++index; } if (balanced && stack.IsEmpty()) { cout << " is well formed..." << endl; } else { cout << " is NOT well formed!!! " << endl; } }// End of Main bool IsOpen(char symbol) { if ((symbol == '(') || (symbol == '{') || (symbol == '[')) { return true; } else { return false; } }// End of IsOpen bool IsClosed(char symbol) { if ((symbol == ')') || (symbol == '}') || (symbol == ']')) { return true; } else { return false; } }// End of IsClosed bool IsWellFormed(char openSymbol, char closeSymbol) { return (((openSymbol == '(') && closeSymbol == ')') || ((openSymbol == '{') && closeSymbol == '}') || ((openSymbol == '[') && closeSymbol == ']')); }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compile four separate times to display different output)
====== RUN 1 ======
Enter an expression and press ENTER.
((
The expression: (( is NOT well formed!!!====== RUN 2 ======
Enter an expression and press ENTER.
(a{b[]}c)The expression: (a{b[]}c) is well formed...
====== RUN 3 ======
Enter an expression and press ENTER.
[(7 * 28) - 1987]The expression: [(7 * 28) - 1987] is well formed...
====== RUN 4 ======
Enter an expression and press ENTER.
{3 + [2 / 3] - (9 + 18) * 12)The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!!
C++ || FizzBuzz – Tackling The Fizz Buzz Test In C++
What is Fizz Buzz?
Simply put, a “Fizz-Buzz test” is a programming interview question designed to help filter out potential job prospects – those who can’t seem to program if their life depended on it.
An example of a typical Fizz-Buzz question is the following:
Write a program which prints the numbers from 1 to 100. But for multiples of three, print the word “Fizz” instead of the number, and for the multiples of five, print the word “Buzz”. For numbers which are multiples of both three and five, print the word “FizzBuzz”.
This seems easy enough, and many should be able to complete a program which carries out a solution in a few minutes. Though, after doing a little research, apparently that is not the case. This page will present one way to carry out a solution to this Fizz-Buzz problem.
There is a small “catch” that some may encounter when trying to solve this problem, and that is the fact that the conditional statement for the number divisible by 15 should come before each sequential conditional statement. Consider this pseudocode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// A simple Fizz-Buzz algorithm using a while loop 'currentNumber' = 1 while('currentNumber' is less than or equal to 100) { if('currentNumber' is divisible by 3) AND ('currentNumber' is divisible by 5) print "FizzBuzz" else if('currentNumber' is divisible by 3) print "Fizz" else if('currentNumber' is divisible by 5) print "Buzz" else // 'currentNumber' is not divisible by 3 or 5 print 'currentNumber' increment 'currentNumber' by one }// http://programmingnotes.org/ |
The portion that may make this problem tricky for some is the fact that the conditional statement for the number divisible by 15 must be checked -before- the conditional statements which checks for numbers divisible by 3 and 5. If the conditional statements are placed in any other order, the end result will not be correct, which is what can make the problem difficult for many.
======= THE FIZZ BUZZ TEST =======
So building upon the pseudocode found from above, utilizing the modulus operator, here is a simple solution to the Fizz Buzz Test
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 2012 // Taken From: http://programmingnotes.org/ // File: fizzbuzz.cpp // Description: Demonstrates the fizz buzz test // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int fizz = 3; int buzz = 5; int endNumber = 100; int fizzBuzz = fizz * buzz; // ^ numbers divisible by 3 and 5 are also divisible by 3 * 5 // start the loop, continue until the counter // reaches the 'end' for (int currentNumber = 1; currentNumber <= endNumber; ++currentNumber) { if (currentNumber % fizzBuzz == 0) // divisible by 3 and 5 { cout<<"FIZZ BUZZ!!\n"; } else if (currentNumber % fizz == 0) // divisible by 3 { cout<<"FIZZ\n"; } else if (currentNumber % buzz == 0)// divisible by 5 { cout<<"BUZZ\n"; } else // not divisible by 3 or 5 { cout<<currentNumber<<endl; } } return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
1
2
FIZZ
4
BUZZ
FIZZ
7
8
FIZZ
BUZZ
11
FIZZ
13
14
FIZZ BUZZ!!
16
17
FIZZ
19
BUZZ
FIZZ
22
23
FIZZ
BUZZ
26
FIZZ
28
29
FIZZ BUZZ!!
31
32
FIZZ
34
BUZZ
FIZZ
37
38
FIZZ
BUZZ
41
FIZZ
43
44
FIZZ BUZZ!!
46
47
FIZZ
49
BUZZ
FIZZ
52
53
FIZZ
BUZZ
56
FIZZ
58
59
FIZZ BUZZ!!
61
62
FIZZ
64
BUZZ
FIZZ
67
68
FIZZ
BUZZ
71
FIZZ
73
74
FIZZ BUZZ!!
76
77
FIZZ
79
BUZZ
FIZZ
82
83
FIZZ
BUZZ
86
FIZZ
88
89
FIZZ BUZZ!!
91
92
FIZZ
94
BUZZ
FIZZ
97
98
FIZZ
BUZZ
C++ || Snippet – Round A Number To The Nearest Whole Number
This page will display a simple implementation of a function which rounds a floating point number to the nearest whole number. So for example, if the number 12.34542 was sent to the function, it would return the rounded value of 12.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
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 |
#include <iostream> #include <cmath> using namespace std; // function prototype double RoundNumber(double floatNumber); int main() { // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber; cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl; return 0; } double RoundNumber(double floatNumber) { // declare variables double intNumber = 0; // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber); // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)
====== RUN 1 ======
Enter in a floating point number to round: 1.3333
1.3333 rounded to the nearest whole number is: 1
====== RUN 2 ======
Enter in a floating point number to round: 35.56
35.56 rounded to the nearest whole number is: 36
====== RUN 3 ======
Enter in a floating point number to round: 19.8728
19.8728 rounded to the nearest whole number is: 20