Hi! I am a beginner to C++ programming and I am completed stumped on one of my homework labs. I will post the homework instructions and what I have done so far. I appreciate any tips or guidance!
Instructions: Prompt the user for a number such as 5 and calculate the square by using pow(variable, 2.0), cube by using pow(variable, 3.0) and 4th power pow(variable, 4.0). Add 5 to the number and repeat the procedure 10 times. In this case up to 50.
What I have done so far:
do
{
cout << "Please enter a number to Square, Cube, and raise to 4th power: ";
cin >> variable;
cout << endl;
cout << "\t" << "Number\tSquare\tCube\t4th Power" << endl;
cout << "\t" << "------\t------\t------\t-------" << endl;
square = pow(variable, 2.0);
cube = pow(variable, 3.0);
fourthP = pow(variable, 4.0);
for (int a = 1; a <= 1; a++) // Outer loop
{
for (int b = 1; b <= 10; b++) // Inner loop
cout << "\t" << variable << "\t" << square << "\t" << cube << "\t" << fourthP << endl;
cout << endl;
}
cout << endl;
cout << "Would you like to continue (Y or N)? ";
cin >> answer;
system("cls");
you can use int 64 to print the values as integers for a while. But it will overflow at some point, so you may not want that. much past 7100ish will overflow uint64_t to the 5th. you can adjust the double printing to look more like integers as well ... look at the cout format specifiers and play with them if you want. http://faculty.cs.niu.edu/~hutchins/csci241/output.htm
and I see furry already fixed the extra variables :)
and I see furry already fixed the extra variables :)
Without code tags and an incomplete code snippet I didn't see the overuse of variables. I simply coded what I knew would work without the excess memory usage.
Another approach for future consideration - using pow is not the best for integers, even though you probably aren't allowed to deviate. <iomanip> gives good control over columns hence <iomanip>, tabs are a student's nightmare and make beginners wonder why C++ is taught.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
#define FORMAT << " " << setw( 12 ) << right <<
int number;
cout << "Please enter a number: "; cin >> number;
for ( auto head : { "x", "x^2", "x^3", "x^4" } ) cout FORMAT head;
cout << "\n\n";
for ( int last = number + 45; number <= last; number += 5 )
{
unsignedlonglong x = 1;
for ( int power = 1; power <= 4; power++ )
{
x *= number;
cout FORMAT x;
}
cout << '\n';
}
}