C+中的循环+;(同时) 我需要在C++中编写一个程序,用户可以在其中进行计算,当计算完成时,程序将询问用户是否想进行另一个计算。我知道如何用Python编写: more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() 我创建了一个char变量,并将其用于循环的头部,但是我不知道如何在C++中实现“输入”函数。我尝试使用cin.get(char\u变量)函数,但程序似乎完全跳过了它。
您可以使用C+中的循环+;(同时) 我需要在C++中编写一个程序,用户可以在其中进行计算,当计算完成时,程序将询问用户是否想进行另一个计算。我知道如何用Python编写: more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() 我创建了一个char变量,并将其用于循环的头部,但是我不知道如何在C++中实现“输入”函数。我尝试使用cin.get(char\u变量)函数,但程序似乎完全跳过了它。,python,c++,loops,Python,C++,Loops,您可以使用cin>>char\u变量以获取值。 别忘了: #include <iostream> using namespace std; #包括 使用名称空间std; 您可以使用do while循环,该循环基本上至少运行一次。它运行,然后检查条件,不像普通while循环检查条件,然后运行。例如: bool playAgain; //conditional of the do-while loop char more; //Choice to play again: 'y' or
cin>>char\u变量代码>以获取值。
别忘了:
#include <iostream>
using namespace std;
#包括
使用名称空间std;
您可以使用do while循环,该循环基本上至少运行一次。它运行,然后检查条件,不像普通while循环检查条件,然后运行。例如:
bool playAgain; //conditional of the do-while loop
char more; //Choice to play again: 'y' or 'n'
string input; /*In this example program, they enter
their name, and it outputs "Hello, name" */
do{
//input/output
cout << "Enter your name: ";
cin >> input;
cout << "Hello, " << input << endl << endl;
//play again input
cout << "Do you want to play again?(y/n): ";
cin >> more;
cout << endl;
//Sets bool playAgain to either true or false depending on their choice
if (more == 'y')
playAgain = true;
else if (more == 'n')
playAgain = false;
//You can add validation here as well (if they enter something else)
} while (playAgain == true); //if they want to play again then run the loop again
bool再次播放//do-while循环的条件
炭多//选择再次播放:“y”或“n”
字符串输入/*在这个示例程序中,它们输入
他们的名字,并输出“你好,名字”*/
做{
//输入/输出
cout>输入;
cout您的程序非常简单。它是这样的:-
#include <iostream>
using namespace std;
int main()
{
char ch='y';
do
{
// compute....
cout<<"do you want to continue ?: "<<flush;
cin>>ch;
}while (ch=='y' || ch=='Y'); // don't for get the semicolon
return 0;
}
简单!希望您的代码能正常工作。如果您使用cin.get,可能会出现以下问题。如果您运行此代码:
cout << "give a number:";
int n;
cin >> n;
cout << "give a char:";
char c;
cin.get(c);
cout << "number=" << n << endl;
其中,cin.get()
似乎被忽略。事实上不是。它读取您在数字后键入的“行尾”。您可以通过添加
cout << "char code=" << (int) c << endl;
cout我是这样写的。我使用cin
从用户那里获取char
值
#include <iostream>
using namespace std ;
int main ()
{
char more;
cout<<"Do you want to do another computation? y/n ";
cin>>more;
while(more=='y'){
cout<<"Do you want to do another computation? y/n ";
cin>>more;
}
}
#包括
使用名称空间std;
int main()
{
炭多;
库特莫尔;
而(更多=='y'){
库特莫尔;
}
}
python在标记中的作用
cout << "char code=" << (int) c << endl;
#include <iostream>
using namespace std ;
int main ()
{
char more;
cout<<"Do you want to do another computation? y/n ";
cin>>more;
while(more=='y'){
cout<<"Do you want to do another computation? y/n ";
cin>>more;
}
}