[英]How to print out the first input/value of a variable? C++
so I was writing a program about printing out the consecutive sum of positive integers starting from 1 and the thing is that I wanted to cout the final sum in a certain form that prints out to me the 'n' I entered at the start of the program but instead it prints out the 'n' after all the calculations have been made. 所以我正在编写一个程序,用于打印从1开始的连续正整数和,而事实是我想以某种形式表示最终和,以打印出我在输入开始时输入的“ n”程序,但在完成所有计算后将打印出“ n”。
#include <iostream>
using namespace std;
int main()
{
int sum,n;
cout << "Enter a number to be added consecutively starting from 1: ";
cin >> n;
do
{
sum = sum + n;
n--;
}
while(n > 0);
cout<<"The consecutive sum starting from 1 to "<< n <<"="<< sum <<endl;
return 0;
}
so what I mean is that in the last cout it prints out 'n' as 1 since that's when 'n' stops going into the do-while loop again. 所以我的意思是,在最后一个cout中,它将“ n”打印为1,因为那是“ n”停止再次进入do-while循环的时候。 I want to print out the 'n' entered at the begining as an input/
我想打印出开头输入的'n'作为输入/
thanks to everyone for all the help and replies! 感谢大家的所有帮助和答复! after reading your replies I wanted to improve it
阅读您的回复后,我想改善它
#include <iostream>
int main()
{
int sum,n;
sum = 0;
std::cout<<"\nEnter a number to be added consecutively starting from 1:";
std::cin>>n;
int t=n;
for (n ; n>0 ; n--)
{
sum = sum + n;
}
std::cout<<"\nThe consecutive sum starting from 1 to "<<t<<" = "<<sum;
return 0;
}
thank you! 谢谢!
Store the value of n into some other variable and use that variable for displaying that value! 将n的值存储到其他变量中,并使用该变量显示该值! or do this
或这样做
#include <iostream>
using namespace std;
int main()
{
int sum,n;
cout << "Enter a number to be added consecutively starting from 1: ";
cin >> n;
cout<<"The consecutive sum starting from 1 to "<< n ;
do
{
sum = sum + n;
n--;
}
while(n > 0);
cout<<"="<< sum <<endl;
return 0;
}
this will give the desired output! 这将提供所需的输出!
You can store it in another variable and print it out at the end: 您可以将其存储在另一个变量中,并在最后打印出来:
#include <iostream>
using namespace std;
int main()
{
int sum = 0, n;
cout << "Enter a number to be added consecutively starting from 1: ";
cin >> n;
int t = n;
do
{
sum = sum + n;
n--;
} while (n > 0);
cout << "The consecutive sum starting from 1 to " << t << "=" << sum << endl;
return 0;
}
Plus, sum will not be automatically set to 0 (initialized) when you define it. 另外,定义和时,sum不会自动设置为0(初始化)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.