如何打印出变量的第一个输入/值? C ++

时间:2017-12-24 14:11:48

标签: c++ c++11 visual-c++

所以我正在编写一个关于从1开始打印出连续正整数之和的程序,事情就是我希望以某种形式输出最终总和,然后打印出“' n&#39 ;我在节目开始时进入,但它打印出了' 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;

}

所以我的意思是,在最后一个cout中它打印出&#39; n&#39;从那以后就是1&#39; n&#39;再次停止进入do-while循环。我想要打印出来的&#39; n&#39;在开头输入作为输入/

提前谢谢! (还在学习)

感谢所有人的帮助和回复!在阅读你的回复之后我想改进它

#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;

}
谢谢你!

2 个答案:

答案 0 :(得分:1)

将n的值存储到其他变量中,并使用该变量显示该值!或者这样做

 #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;

}

这将提供所需的输出!

答案 1 :(得分:0)

您可以将其存储在另一个变量中并在最后打印出来:

#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;

}

另外,定义时,sum不会自动设置为0(初始化)。