I have this code:
#include <iostream>
using namespace std;
double sqrt(double n)
{
double x;
double y = 2; //first guess is half of the given number
for (int i = 0; i<50; i++)
{
if (n>0)
{
x = n / y;
y = (x + y) / 2;
}
if (n==0)
{
return 0;
}
}
return y;
}
int main()
{
cout << "Square Root Function" << endl;
double z=0;
while (true)
{
cout << "Enter a number = ";
cin >> z;
if (z<0)
{
cout<<"enter a positive number"<<endl;
continue;
}
cout <<"the square root is "<< sqrt(z) << endl;
}
return 0;
}
and it would show this result:
Square Root Function
Enter a number = 12
the square root is: 3.4641
but now the code is showing these results:
Square Root Function
1 //my input
Enter a number = the square root is 1
2 //my input
Enter a number = the square root is 1.41421
It seems like the cout will only show up first if an endl was added after the string. This just started happening recently. Is there a way I can fix this to show the proper output?
std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.
You can also use std::cout << std::endl, which writes a line break and then flushes, thats the reason your code shows this behavior.
Change your int main() to
int main(){
std::cout << "Square Root Function" << std::endl;
double z=0;
while (true){
std::cout << "Enter a number = " << std::flush
/*^^^^^^^^^^*/
std::cin >> z;
if (z<0){
std::cout << "enter a positive number" << std::endl;
continue;
}
std::cout << "the square root is " << sqrt(z) << std::endl;
}
}
EDIT: The XCode Problem Since you use XCode another thing could cause trouble. It seems like XCode doesn't flush buffers until a line break; flushing doesn't help. We had several questions about it lately (e.g. C++ not showing cout in Xcode console but runs perfectly in Terminal). It seems to be a bug in a XCode version.
Try to flush your buffer as described by me and try to compile it using terminal. If it works there your code is fine and it's an XCode issue.
Related
Summarize the problem:
My goal is to generate odd numbers up to a limit, store them in a vector then output the square of them.
Describe what you've tried:
So far, I used the #include < cmath > at the start before int main(), then I used a couple of if statements to check whether the limit is zero, if so I output an error message. If the limit is >0 then I squared the odd numbers using pow(num,2) however, this does not work and gives wrong answer. For example, it gives the square of 13 as 600ish, that is obviously wrong. Please give advice. My full code is here, it is very simple so I did not put much comments in there:
#include<iostream>
#include<format>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int limit{};
cout << "Enter a limit of odd integers: \n";
cin >> limit;
vector<int>oddnumb(limit);
if (limit == 0)
{
cout << "You MUST enter a number>0, then restart the program. \n";
return 0;
}
if (limit > 0)
{
cout << "Odd numbers are as follows: \n";
for (size_t i{}; i < limit-1; ++i)
{
oddnumb[i] += ++i;
cout << oddnumb[i] << endl;
}
cout << "Squared odd numbers follow: \n";
for (size_t i{}; i < limit - 1; ++i)
{
oddnumb[i] += ++i;
cout << pow(oddnumb[i],2) << endl;
}
}
I've written up a working version of what you want to do. I urge you to figure it out yourself first, that's the best way to learn, and then check your version against what I've got here. Note that this is certainly not the best way to do it. But I wrote it in a way that should be easy to understand. In programming there are lots of ways to tackle any problem, the best way is arguably... the way that works! Good luck in your journey with C++!
#include <cmath>
#include <iostream>
#include <vector>
int main()
{
double input{};
while (input < 1)//validate that input is greater than 0 here by looping if it isn't
{
std::cout << "Enter a limit of odd integers: ";
std::cin >> input;
if (input < 1)//if a valid range is entered this is never shown
{
std::cout << "Enter a valid range. Greater than 0. \n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::vector<double> oddNumbers{};
std::cout << "Odd numbers:\n";
//notice we're starting this loop at 1, since 0 is even we just avoid it
for (double i = 1.0; i <= input; i += 2.0) //you can add more than just 1 to i
{
oddNumbers.push_back(i);// here we're putting the value of i at the back of the vector
std::cout << i << " squared is " << pow(i, 2.0) << '\n';
//we could avoid using a vector by printing the squared value of i within this loop
}
std::cout << "Squared Odd Numbers:\n";
//we do need to start this loop at 0 to access the first element of the vector
for (unsigned int i = 0; i < oddNumbers.size(); i++)
//we also increase i by just one each time to access each element we stored
{
std::cout << pow(oddNumbers[i], 2.0) << '\n';
}
return 0;
}
So I am making a program that will create a square based on the users desired size. My code so far reads the value, prints out the top of the square but i'm getting caught up on how to set up the sides because of a nested loop I've created. The issue here is that I need for the loop to reset it's values every time it exists.
Here's my code so far:
#include <iostream>
using namespace std;
int main(int,char**) {
int x;
int z=1;
int l=0;
int n=0;
int q=1;
int m=0;
int o=0;
do{
cout << "Enter length between 0 and 64 (-1 to exit): ";
cin >> x;
if (x>-1&&x<64){
cout << "+";
for (;x-2!=n;++n){
cout << "-";
}
cout << "+" << endl;
}
else{
cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit.";
}
do {
cout << "|";
do {
//cout << " ";
//++m;
//}while (x-2!=m);
cout << "|" << endl;
++o;
}
while (x-2!=o);
++z;
}
while (z!=5);
}
The commented out portion is where the program is getting caught up at, it seems that when I increment m until it exits the do while loop, it holds onto the value that it was incremented to. I know that a continue statement breaks from the loop and begins a new iteration of the loop but it doesn't seem to want to fit inside the do-while loop even if i create an if statement such as
if (x-2==m){
continue;
}
Any help would be appreciated
Just put m = 0; before the loop.
m = 0;
do {
cout << ' ';
++m;
} while (x-2 != m);
Or use a for loop instead;
for (int m = 0; m != x-2; m++) {
cout << ' ';
}
This is the more common idiom for repeating something a certain number of times, since you can see all the conditions related to the loop in a single place.
This question already has answers here:
How to start from beginning of the program
(6 answers)
Closed 6 years ago.
I just made code that calculates the multiplication tables, based on user input. The problem is that after I print the results, the program closes and I need to relaunch it to get different input and results.
I want to get the results and press a key to get a new value from the user: I don't want to be constantly closing and opening the the program. How can I do this?
This is my code:
#include <iostream>
using namespace std;
int main()
{
int a, range;
cout << "Introduce value: ";
cin >> a;
printf("\n");
cout << "Introduce range: ";
cin >> range;
printf("\n");
for (int i = 1; i <= range; ++i)
{
cout << a << " * " << i << " = " << a*i << endl;
}
printf("\n");
system("pause");
}
Add something like while(1)
#include <iostream>
using namespace std;
int main()
{
while(1){
int a, range;
cout << "Introduce value: ";
cin >> a;
printf("\n");
cout << "Introduce range: ";
cin >> range;
printf("\n");
for (int i = 1; i <= range; ++i)
{
cout << a << " * " << i << " = " << a*i << endl;
}
printf("\n");
system("pause");
}
}
Since the condition inside the while statement will always be true, your code here will loop forever!
If you want to press a key to determine if you want to continue with another value use the do while loop.
int main(void){
char c;
do{
//......your code
cout<<"Do you want to continue?"; // press 'y' if yes
cin>>c;
}while(c=='y');
return 0;
}
Press 'y' to continue or anything else to stop.
With this code you dont need system("Pause") at the end.
The prompt is to start with a random number and to keep replacing that number repeatedly under the conditions that (1) if the number is even, you divide it by two and (2) if the number is odd, you multiply it by three then add one.
So, for example:
If the number was 13, then the output would be: 40 20 10 5 16 8 4 2 1
(Also the program must stop after the value of 1 is reached)
#include <iostream>
using namespace std;
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
while(x%2==1)
{
x=x*3+1;
cout << x << " ";
lengthcount++;
}
if(x==1)
{
return 1;
}
cout << "Length:" << lengthcount << endl;
}
This is what I have so far. But when I compile and run the code only the first value of 40 appears. Not the rest of components. I'm assuming it has to do with the loops not connecting with one another. How do I get it so that the output of one loop would go to the other loop and back?
Two sequential loops aren't connected, and there's no way that you can or should make them so.
Instead, have a single loop, with an if/else inside it to handle the odd/even cases respectively.
The way the code currently is, neither the division by 2^n, nor the 3n+1 operation can be performed more than once. You need to have an outer loop around these operations.
The correct way to exit a loop is with the break keyword, not return.
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
while(true) {
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
if(x==1)
{
break;
}
x=x*3+1;
cout << x << " ";
lengthcount++;
}
cout << "Length:" << lengthcount << endl;
}
How do I get it so that the output of one loop would go to the other loop and back?
You syould introduce loop in your code.
Furthermore, because 1%2==1 is true, x==1 should always be false after while(x%2==1).
An example of fixed code:
#include <iostream>
using namespace std;
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
for(;;)
{
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
if(x==1) // check if the value of 1 is reached
{
break;
}
while(x%2==1)
{
x=x*3+1;
cout << x << " ";
lengthcount++;
}
}
if(x!=1) // x should be 1 in here
{
return 1;
}
cout << "Length:" << lengthcount << endl;
}
I have to make a program for a class that displays one star for every three degrees for each temperature read from an input file. I think I did ok, the code compiles. However, when I actually run it, I have a few problems:
1) when I run it without pressing ctrl+f5 in codelite it exits immediately, even though I have 'return 0;' at the end.
2) the console only shows stars for maybe half of the numbers, the rest are blank.
3) the numbers aren't lining up although I have set them all to the same width in my loop.
Here's what I see when I use ctrl+f5: http://imgur.com/w6jqPp5
Here's my code:
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
//declare variables for input/loops
string graphLine = " | ";
int tempCount = 0;
int tempStars;
int tempValue;
int printedStars;
//Title
cout << "Welcome to the Hourly Temperature Bar-Graph Maker 1.0!" << endl;
//read input file, name it "tempData"
ifstream tempData;
tempData.open("temperatures.txt");
//display error if the input file read failed
if(!tempData) {
cout << "ERROR: The input file could not be read." << endl;
return 0;
}
cout << "Temperatures for 24 hours(each asterisk represents 3 degrees): " << endl;
//print the temperature range(horizontal label for graph)
cout << "-30 0 30 60 90 120" << endl;
//read a temperature, output the bar for each temperature
while (tempCount < 24) {
//read in temperature value
tempData >> tempValue;
//distinguish between negative and positive temperatures
if(tempValue >= 0) {
tempStars = tempValue/3;
cout << tempValue << setw(5) << graphLine;
//print the appropriate number of asterisks for the temperature
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << endl;
}
//print the stars before the line
else {
tempStars = tempValue/3;
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << tempValue << setw(5) << graphLine << endl;
}
tempCount++;
}
tempData.close();
return 0;
}
The program is just finishing normally - put a call to cin.getline or some other input call if you want it to wait. Alternatively run it through the debugger and put a breakpoint on the return 0 line.
You don't initialize or reset printedStars before you use it. Put printedStars = 0; before your star printing loops.
Move the setw(5) bit in the cout calls to before the value, so the value is output with a width of 5.