Please note that I am just starting C++.
I am working from Bjarne Stroustrup's book "Programming Principles and Practice Using C++ 2nd Edition" and am on a Drill at the end of chapter 4.
These are the instructions so far:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.
Change the program to write out "the smaller value is:" followed by the smaller of the numbers and the "larger value is:" followed by the larger value.
Augment the program so that it writes the line "the numbers are equal" (only) if they are equal.
Change the program so that it uses doubles instead of ints.
5. Change the program so that it writes out "the numbers are almost equal" after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100.
This is where I am stuck.
First, I do not understand what "if the two numbers differ by less than 1.0/100." means. Does that mean if the two numbers are within 100 numbers of each other?
Second, how do I determine "if the two numbers differ by less than 1.0/100"? (The more simple the solution the better.)
Here is my code so far:
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if (v1 > v2)
cout << "The smaller of the two numbers is: " << v2 << "\n";
else if (v1 == v2)
cout << "The numbers are equal. \n";
else
cout << "The smaller of the two numbers is: " << v1 << "\n";
cout << "Enter two numbers: ";
}
}
Thank you for taking the time to read this.
This may be what it means
if(std::abs(v1-v2)<0.01)
#Walter 's answer may also be correct. It depends on the intention of the original question, which is not quite clear. For example, if #Walter 's version is used, then for v1 = v2 = 0.0, the program would say they are not close.
I think it means that the relative difference between the two floating point numbers is less than 1 part in 100, i.e.
if(std::abs(x-y)<0.01*std::max(std::abs(x),std::abs(y)))
Here I use the maximum of the absolute values as reference. You may also use the mean, but taking (the absolute of) either value is less advisable because it's not symmetric.
I have understood the assignment the following way:
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if ( v1 < v2 )
{
cout << "The smaller of the two numbers is the first number: " << v1 << "\n";
cout << "The largest of the two numbers is the second number: " << v2 << "\n";
}
else if ( v2 < v1 )
{
cout << "The smaller of the two numbers is the second number: " << v2 << "\n";
cout << "The largest of the two numbers is the first number: " << v1 << "\n";
}
if ( abs( v1 - v2) < 1.0 / 100 )
{
cout << "The numbers are almost equal. \n";
}
cout << "Enter two numbers: ";
}
}
This is a dead topic but I thought I should clarify this. The difference between 2 numbers is the result of the subtraction between the largest number and the smallest number. Therefore you need to declare 2 variables to keep track of which is the smallest and which is the largest in each of the if-else statements. Therefore the code should look like this.
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0, larger, smaller;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if (v1 > v2)
{
cout << "The smaller of the two numbers is: " << v2 << "\n";
smaller = v2;
larger = v1;
}
else if (v1 == v2)
{
cout << "The numbers are equal. \n";
}
else if(v1 < v2)
{
cout << "The smaller of the two numbers is: " << v1 << "\n";
smaller = v1;
larger = v2;
}
if((larger-smaller)<1.0/100)
{
cout << "the numbers are almost equal" << endl;
}
cout << "Enter two numbers: ";
}
}
return 0;
This is my version:
#include "std_lib_facilities.h" // Custom header file for this book
int main() {
double a, b;
while (cin >> a >> b) {
if (a < b) {
cout << "The smaller value is: " << a << '\n'
<< "The larger value is: " << b << '\n';
if ((b - a) < (1.0 / 100))
cout << "The numbers are almost equal\n";
}
else if (a > b) {
cout << "The smaller value is: " << b << '\n'
<< "The larger value is: " << a << '\n';
if ((a - b) < (1.0 / 100))
cout << "The numbers are almost equal\n";
}
else {
cout << "The numbers are equal\n";
}
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
double n1, n2;
double smaller, larger;
double differ=1.0/100;
string small ="The smallest number is: ";
string large ="The largest number is: ";
string equal ="\nBoth numbers are almost equal\n";
while(cin>>n1>>n2){
if (n1==n2){
cout<<"Both number are abslute equal!!!";
continue;
}
else if(n1>n2){
cout<<small<<n2<<" ";smaller=n2;larger=n1;}
else if (n1<n2) {
cout<<large<<n2<<" ";larger=n2;smaller=n1;}
if(larger-smaller<=differ)
cout<<equal;
}
return 0;
}
Even though it's an old thread I've come across it whilst working through the the same book. In case any more students do the same, here's what I've come up with using 1.0 / 100 as the literal 0.01:
#include "../../std_lib_facilities.h"
double lower(double int1, double int2) //function to calculate the smallest of two doubles
{
if (int1 > int2)
return int2;
else
return int1;
}
double upper(double int1, double int2) //function to calculate the largest of two doubles
{
if (int1 < int2)
return int2;
else
return int1;
}
int main()
{
double val1, val2;
while (cin >> val1 >> val2)
{
double smallest = lower(val1, val2);
double largest = upper(val1, val2);
if (val1 == val2)
{
cout << "The values are equal.\n";
}
else
{
cout << "The smaller value is: " << smallest << "\n";
cout << "The larger value is: " << largest << "\n";
if (abs(largest - smallest) < 1.0 / 100)
{
cout << "The numbers are almost equal.\n";
}
}
}
}
By this point in the book you too should have already covered functions and can utilise them here to keep your main function tidy.
"5. Change the program so that it writes out "the numbers are almost equal" after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100."
The reason why you do not understand what the author is asking is because the question is based on SPECIFICALLY pure basic mathematical speech (Was hard for me to understand "math" word questions too). It's one of those questions you can only understand if you understand the grammar of math, complete the book: "Practical Algebra: A Self-Teaching Guide" finish that book and then read c++ from Bjarne, it's going to be extremely difficult if you can't understand basic mathematical grammar specially for hardcore programming language c++.
"the number are almost equal"
It is a figure of speech, doesn't mean that there's a special C++ function or library for it.
"if the two numbers differ by less than 1.0/100."
Literally means the difference of two numbers are equal to 1.0/100 which is 0.01, which means for example if (9.99 - 10) = 0.01. But there's more to the question which makes it tricky, not only the Author is asking for the difference of 0.01 but the difference has to be less than 0.01. so basically you can write the formula such as:
double a; // use the built-in type keyword "double" since the values are in decimal.
double b;
if ((a - b) < 0.01)
{
//statement code goes here.
}
Also you deserve a cookie since you're reading a C++ book from it's creator.
This has been working for me.
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
double x=0;
double y=0;
while(cin >> x ,cin >> y)
if (x > y){
cout << "The larger value is " << x << " the smaller value is " << y << "\n";
if (x - y < (1.0/100)) {
cout << "the numbers are almost equal" << endl;
}
}
else if (x < y){
cout << "The larger value is " << y << " the smaller value is " << x << "\n";
if (y - x < (1.0/100)) {
cout << "the numbers are almost equal" << endl;
}
}
else if (x == y)
cout << "the numbers must be equal\n";
}
Related
When I check the values inside of the homework vector using cout it seems to only be returning the value inside homework[0]. Can somebody look over my code and let me know where I'm going wrong?
int main()
{
cout << "Please enter midterm and final: " << endl;
double midterm, gfinal;
cin >> midterm >> gfinal;
cout << "Enter all your homework grades, " << endl;
double x;
cin >> x;
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x);
if (homework.size() == 0)
{
cout << endl << "You need to enter at least one number";
return 1;
}
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
int mid = homework.size() / 2;
cout << "The below is mid" << endl;
cout << mid << endl;
double median;
if (homework.size() % 2 == 0)
median = (homework[mid - 1] + homework[mid]) / 2;
else
median = homework[mid];
//streamsize prec = cout.precision(3);
cout << "Your course grade is "
<< 0.2 * midterm + 0.4 * gfinal + 0.4 * median << endl;
//cout.precision(prec);
return 0;
}
This is the specific code that is causing me confusion:
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
When the program starts it asks for 2 values, so I plugged in 100 100.
Then it asks for 3 values so I used 80 90 100 the cout of all the homework positions is showing 80 when I am expecting 80 90 100.
The actual program works as the final cout returns 92 as expected.
In your code:
double x;
cin >> x; // <-- reading from cin only once
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x); // <- inserting same value three times
you are reading from cin only once, i.e., you are reading a single value. Then, you are inserting that read value three times into the vector homework. Therefore, homework[0], homework[1] and homework[2] contain the same value.
Consider placing cin >> x inside the while loop to read three times from cin instead of just once, i.e., read from cin on each iteration of the loop:
vector<double> homework;
while (homework.size() < 3) {
double x;
cin >> x;
homework.push_back(x);
}
In addition to the bug that El Profesor pointed, for iterating a vector in modern C++, all you have to do is:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> homework{ 70,80,90 }; // For the example
// "See what is inside the vector":
for (auto grade : homework)
std::cout << grade << '\n';
}
So, the bugs have been fixed already. I will add a "more-C++"-style solution using STL algorithms.
For filling the vector, I will use std::copy_n. Meaning, read n values from std::cin and insert them into the target vector.
And for your question
How can I see what is inside a vector?
the solution is, iterate over the elements in the vector and copy the vectors values to ctd::cout. For this we will use the std::ostream_iterator
Please note: I always use qualifed names lke std::cout. Please consider. And I rarly use std::endl, becuase this always call flush, which is in most cases not needed. Also: All variables should always be initialized. Always.
And then, I added many comments. Please also consider. This improves the code readability and quality drastically.
Please see:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
constexpr size_t NumberOfHomeworkGrades = 3U;
int main()
{
// Print title and ask use to enter data
std::cout << "\nCalculation of course grade\n\nPlease enter midterm and final: " << '\n';
double midterm{ 0.0 };
double gfinal{ 0.0 };
std::cin >> midterm >> gfinal;
// Ask the use to enter the howmwork grades
std::cout << "Please Enter "<< NumberOfHomeworkGrades << " homework grades\n";
// Get the data from the user and put it into the vector
std::vector<double> homeworkGrades{};
std::copy_n(
std::istream_iterator<double>(std::cin), // We will iterate over std::cin and read data
NumberOfHomeworkGrades, // Over all we read data NumberOfHomeworkGrades times
std::back_inserter(homeworkGrades) // And we psuh the data into our homeworkGrades-vector
);
// Show the vector before sorting. Simply copy all data in the vector to std::cout using the ostream_iterator
std::cout << "\n\nEntered grades before sort\n";
std::copy(homeworkGrades.begin(), homeworkGrades.end(), std::ostream_iterator<double>(std::cout, "\n"));
// Sort the vector here
std::sort(homeworkGrades.begin(), homeworkGrades.end());
// Show the vector adter sorting. Simply copy all data in the vector to std::cout using the ostream_iterator
std::cout << "\n\nSorted grades\n";
std::copy(homeworkGrades.begin(), homeworkGrades.end(), std::ostream_iterator<double>(std::cout, "\n"));
// Calculate the median
double median{ 0 };
// First calculate the mid, to do the calculation only one time and to show the result
size_t mid{ homeworkGrades.size() / 2 };
if (!homeworkGrades.empty())
if (homeworkGrades.size() % 2 == 0)
median = (homeworkGrades[mid - 1] + homeworkGrades[mid]) / 2;
else
median = homeworkGrades[mid];
// Show the result to the user
std::cout << "\n\nThe mid value is (maybe truncated): " << mid
<< "\nThe median value is: " << median
<< "\n\nYour course grade is: " << 0.2 * midterm + 0.4 * gfinal + 0.4 * median << '\n';
return 0;
}
This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
Hi guys I'm rather new to programming and working my way through Stroustrup's "Programming, Principles and Practice Using C++" and I've come to a complete standstill at the end of Chapter 3 with an exercise asking you to write a piece of code that does a number of calculations involving 2 numbers which includes finding the ratio of the numbers. Unfortunately this hasn't been covered at all in the book and I'm tearing my hair out trying to figure it out by myself, only able to find examples of code way to advanced for my small little brain.
The code I have at the moment is:
double ratio;
if (val2 > val1)
ratio = (val2 / val1);
if (val2 < val1)
ratio = (val1 / val2);
cout << "The ratio of " << val1 << " and " << val2 << " is 1:" << ratio << '\n';
which works fine for numbers that equate to a whole ratio (e.g. 100 and 25) however despite me setting the variable "ratio" as a double it removes any decimals from the answer in cases of non whole number ratios. Can anyone tell me where I'm going wrong?
When dividing integers the result is integer (integer arithmetics is used):
11 / 2 == 5
11 % 2 == 1 /* remainder */
and when dividing floating point values the result is floating point as well:
11.0 / 2 == 5.5
11 / 2.0 == 5.5
((double) 11) / 2 == 5.5
In your case
double ratio = (val2 / val1);
you have an integer division and only after the disvison performed the outcome of it is cast to double. You can either declare val2 and val1 as double:
double val1;
double val2;
or cast at least one argument of the ratio to double:
double ratio = ((double)val2) / val1;
The fact that result type is double doesn't matter if the original division is performed on integral types (truncating the decimal part).
So to solve your problem, either:
Use a floating point type for the input numbers as well
Cast one of the numbers to a floating point type before division
I did the whole problem from Stroustrup's "Programming, Principles and Practice Using C++. Here is the codes although no comments.
int main()
{
/** --------Numbers-----*/
int val1;
int val2;
double largest; //I'll store here the largest value
double smallest; //I'll store here the smallest value
cout<< " Enter two Numbers to play with\n";
while(cin>> val1>>val2){
if(val1<val2){
cout<< "smallest: "<<val1<<endl;
cout<< "largest: "<<val2<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val2;
smallest=val1;}
if(val1>val2){
cout<< "smallest: "<<val2<<endl;
cout<< "largest: "<<val1<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val1;
smallest=val2;}
int their_sum=val1+val2;
int their_product=val1*val2;
int their_diff=val1-val2;
double ratio1;
ratio1=largest/smallest;
cout<<"Sum: "<<their_sum<<endl;
cout<<"Difference: "<<their_diff<<endl;
cout<<"Product: "<<their_product<<endl;
cout<<"Ratio: "<<ratio1;
}
return 0;
}
There is nothing new in this code, everything was covered in the previous chapters.
If at all you need ratio of two numbers say a,b in the form of n:m (where n>=1) then simply find the GCD(a,b) and divide a,b with this result.
eg:
a=4,b=6;
GCD(a,b)=2;
n=4/2=>2
m=6/2=>3
so ratio of 4 and 6 is 2:3
#include<iostream>
using namespace std;
class Test
{
public:
void check()
{
int x,y;
cout<<"Enter 1st number";
cin>>x;
cout<<"Enter 2nd number";
cin>>y;
int a;
int d= gcd(x,y);
cout<< x/d << " : " << y / d << endl;
}
int gcd(int x, int y) // 14, 21
{
int d;
if(y>x)
{
y=x+y;
x=y-x;
y=y-x;
}
for(int i=1; i<=y; i++)
{
if(x%i==0 && y%i==0 )
{
d=i;
}
}
return d;
}
};
int main()
{
Test t;
t.check();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val1,val2;
cout << " Enter two integer values followed by enter" << endl << endl;
cin >> val1;
cin >> val2;
if(val1 < val2) // To determine which value is larger and which one is smaller
{
cout << val1 << " is smaller than" << val2 << endl << endl << "And" << val2 << " is larger than " << val1 << endl<<endl;
}
enter code here
else if( val2 < val1)
{
cout<<val2 <<" is smaller than"<< val1<<endl<<endl<<"And"<< val1 << " is larger than "<< val2<< endl << endl;
}
cout << "The sum of "<< val1<<" and "<<val2<<" is "<< val1+val2<<endl<<endl;
// diplaying the sum of the two numbers
enter code here
cout << " The difference between "<<val1<< " and "<<val2<< " is " << val1-val2<<endl;
// displays the difference of val2 from val1
cout << " The difference between "<<val2<< " and "<<val1<< " is " << val2-val1<<endl;
// displays thr difference of val1 fromval2
enter code here
enter code here
cout << " The product of " <<val1<< " and " << val2<< " is " << val1*val2<< endl<<endl;
// displaying the product of val1 and val2
enter code here
enter code here
enter code here
// now to diplay the ratio of the two numbers
double ratio1;
cout << " The ratio of "<<val1<<" and "<<val2<<" is ";
if(val1 < val2)
{
ratio1= ((double)val2) /val1;
cout << ratio1;
}
else if(val1 > val2)
{
ratio1= ((double)val1) /val2;
cout << ratio1;
}
}
could you please help me with solving simple problem? I am very fresh with C++ and learning from book "Programming: Principles and Practice Using C++ by Bjarne Stroustrup". I have never learnt C++ before so I am not familiar with many useful features. The drill says:
"6. Now change the body of the loop so that it reads just one double
each time around. Define two variables to keep track of which is the
smallest and which is the largest value you have seen so far. Each
time through the loop write out the value entered. If it’s the
smallest so far, write the smallest so far after the number. If it is
the largest so far, write the largest so far after the number"
I do not know how to do this correctly without using vector. Here is my code:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
And here are previous steps, these I have solved with code above:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
Could you give me some hint how to do step 6.? I had some ideas but none of them worked..
Here is new code:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
I do not know how to do this correctly without using vector.
You do not need vector for this. The description correctly says that two variables would be sufficient:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
Modify your loop to read into a, not into both a and b. Check the newly entered value against smallestSoFar and largestSoFar, do the printing, and re-assign smallest and largest as necessary. Note that the first time around you should see both printouts - for largest so far and for smallest so far.
Based on the knowledge that you are suppose to know at the current stage for the this assignment. The code should go something like this:
#include < iostream>
#include < cstdlib>
int main() {
double num_1 = 0;
double num_2 = 0;
double largest = 0;
double smallest = 0;
bool condition1 = true;
while (true) {
std::cin >> num_1;
if (num_1 > largest){
largest = num_1;
}
else if (num_1 < smallest) {
smallest = num_1;
}
std::cout << "The largest so far: " << largest << std::endl;
std::cin >> num_2;
if (condition1) {
smallest = largest;
condition1 = false;
}
if (num_2 < smallest) {
smallest = num_2;
}
else if (num_2 > largest) {
largest = num_2;
}
std::cout << "The smallest so far: " << smallest << std::endl;
}
system("pause");
return 0;
}
double large = 0;
double small = 0;
double input;
int counter = 0;
while (counter < 5) {
cin >> input;
cout <<"Large value: "<< large << '\t' <<"Small value: "<< small\
<< '\t' <<"Input value: "<< input << '\n';
if (input < small) {
cout << "The smallest value is " << input<<\
"\nthe largest value is "<< large<<'\n';
small = input;
}
else if (input > small&& input < large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << large<<'\n';
}
else if (input > small&& input > large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << input << '\n';
large = input;
}
counter += 1;
I went thru so many version of the algorithm to sort smallest and largest that my brain is fried. The book up to this point and searching online haven't helped at all.
I'm having difficulties at saving the last.
I used 3 in, 10 cm and 5 cm as test cases. Entering 3 in first, becomes the largest, entering 5 cm second becomes smallest and then 10 cm becomes smallest again. Tried different version for over 2 hours, even re-wrote that entire section. In the book Programming Principles and Practices using C++, its in the review section, before that I cant find anything to help me out.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
vector<double>all_meters;
double smallest= 0,print_smallest, largest = 0,print_largest, num = 0;
string unit, s_input, num_s_input, small_unit, large_unit;
while(cin.good()){
cout << "\n\t\t\t\tEnter '|' to exit.\n\n";
cout << "\t\tNumber to compare followed by white space and unit:";
cin >> num_s_input;
if(num_s_input.compare("|") == 0 || (s_input.compare("|") == 0)){
double sum = 0;
for (double x : all_meters) sum+=x;
cout << "Sum: " << setprecision(4) << sum << "m\n";
cout << "Smallest number: " << print_smallest << small_unit << endl
<< "Largest number: " << print_largest << large_unit << endl
<< "Total number of values: " << all_meters.size() << endl
<< "All the entered numbers converted to meters are: \n";
for (double i = 0; i<all_meters.size(); ++i){
cout << all_meters[i] << setprecision(2) <<"m ";
}
cout << "\nAlright now, goodbye then !\n" << endl;
break;
}
else{
cin >> s_input;
num = strtod(num_s_input.c_str(), NULL);
unit = s_input;
double meter = 0;
if(unit=="cm"){
meter = num / 100;}
else if(unit=="in"){
meter = num / 39.370;}
else if(unit=="ft"){
meter = num / 3.2808;}
else if(unit=="m"){
meter = num;}
else {
cout << "\n\tYou entered wrong unit!\t\n";}
if(largest==0){
largest = meter;
print_largest = num;
large_unit = unit;
cout << num << unit << " largest so far.\n";
}
else if(smallest==0&&meter<largest){
smallest = meter;
print_smallest = num;
small_unit = unit;
cout << num << unit << " smallest so far.\n";
}
else if(largest<meter){
largest = meter;
print_largest = num;
large_unit = unit;
cout << num << unit << " largest so far.\n";
}
else if(smallest>meter){
smallest = meter;
print_smallest = num;
small_unit = unit;
cout << num << unit << " smallest so far.\n";
}
all_meters.push_back(meter);
sort(all_meters.begin(),all_meters.end());
}
}
}
Managed to solve it without using limit, added the new changes to the code. Thanks for the help guys !
More than likely your problem comes from the fact that you are initializing smallest to 0. If you never enter anything smaller than 0 then smallest will never change.
When finding the minimum and maximum values you want to set the the initial value to the largest or smallest number respectively that it can hold. So in this case we would use
double smallest = std::numeric_limits<double>::max();
double largest = std::numeric_limits<double>::lowest()
double num = 0;
This was anything in your data set should be less than smallest and everything should be grater than largest.
This does require #include <limits>
You need to choose a standard unit of measure. The question suggests meters, so use that (you can use float or double for this, depending on what precision you need).
The problem is then simple, create some variables for the sum, smallest seen, and largest seen, the for each new input, convert to the standard format, and update the variables.
The solution (to get you started, not working code) might look something like this:
// You can represent the different types of units as integers
float convertToMeters(float unconvertedValue, int unit) {
// Convert unconvertedValue based on unit
}
float smallest = std::numeric_limits<float>::max();
float largest = std::numeric_limits<float>::lowest();
float sum = 0.0f;
// Update for each new input
while (new_input) {
float convertedValue = convertToMeters(new_value, unit);
// Update total
sum += convertedValue;
// Update smallest and largest
if (convertedValue > largest) largest = convertedValue;
else if (convertedValue < smallest) smallest = convertedValue;
}
As Nathan mentioned, #include <limits> for the limits.
So I have this program:
#include <iostream>
using namespace std;
bool prime(int input)
{
// cout << "pinput: " << input << endl;
int i = ((input/2) + 1);
// cout << "pi: " << i << endl;
int c;
for (i>0; i--;){
//cout << "pi: " << i << endl;
if (input == 3 || input == 2){
// cout << "true" << endl;
return true;
}
if (input == 1){
// cout << "pi = 1" << endl;
return false;
}
c= input%i;
if (c==0 || i == 1 ){
// cout << "false" << endl;
return false;
}
else if (c!=0 && i<4){
// cout << "true" << endl;
return true;
}
}
return 0;
}
int factor(int input){
// cout << "finput: " << input << endl;
int i = (input/2) + 1;
int c;
int e;
bool d = false;
for (i>0; i--;){
// cout << "fi: " << i << endl;
c = input%i;
if (c==0){
d = prime(i);
if (d==true){
// cout << "found" << endl;
return i;}
}
if (i==1){
// cout << "fi = 1";
return 0;
}
//cout << "not prime" << endl;
}
return 0;
}
int main(){
int woot;
cout << "Please insert quater: " <<endl;
cin >> woot;
int answer;
answer = factor(woot);
if (answer == 0)
cout << "no prime factors" << endl;
else
cout << "answer is: " <<answer << endl;
return 0;
}
It seems to work until I put a really big number in like more specifically the number 600851475143, in which case I always get different answers when I run that number now I'm pretty sure it's just exceeding the size of it's variable type. Now then I was looking and I can't find the right variable type for a number that big, I int and long seem to be for numbers that are for numbers up to 4294967295 if unsigned however that is only 10 digits long, mine is 12. What type of variable should I use? Or will that even fix the problem? The program is to find the largest prime factor of a number (Euler problem 3). Any tips links or advice would be appreciated. And of course an answer extra appreciated! :D
Interesting typo alert!
This is unlikely to be doing what you think it is doing...
for (i>0; i--;){
While it is perfectly legal syntax, and will loop the correct number of times, the value of i inside the loop is (probably) going to be one less than you intended...
% cat 4237157.c++
#include <iostream>
int main()
{
{
std::cout << "Your loop: " << std::endl;
int i = 10;
for (i>0; i--;)
{
std::cout << i << std::endl;
}
}
{
std::cout << "More conventionally: " << std::endl;
for (int i = 10; i > 0; i--)
{
std::cout << i << std::endl;
}
}
return EXIT_SUCCESS;
}
% g++ -o 4237157{,.c++}
% ./4237157
Your loop:
9
8
7
6
5
4
3
2
1
0
More conventionally:
10
9
8
7
6
5
4
3
2
1
The syntax for a for-loop in C-like languages is:
for (variable initialization; conditional; variable increment)
You are evaluating "i>0" instead of doing any initalization. This may as well be blank. Then you are evaluating whether i-- is zero. Since i is post-decremented, your loop starts with i being one less than it was initialized with before the loop, executes until (and including) being equal to zero and then terminates.
A lot of the problems on Project Euler call for arbitrary-precision arithmetic, which isn't covered by the C++ standard library.
Have a look at the C++ Big Integer Library.
If you want arbitarily big numbers, you need an arbitary precision arithmetic library
unsigned long 4294967295
unsigned long long 18446744073709551615
unsigned long long is not standard C++, but most compilers support it as an extension. The maximum should be at least 2^64 - 1, which is more than enough.
If you later want even larger numbers, you can use a arbitrary precision library such as GMP. They have a C++ interface.