如何正确终止此循环?

How do I terminate this loop properly?

本文关键字:循环 终止 何正确      更新时间:2023-10-16

我正在尝试制作一个程序,它要求用户输入一个我最终将计算的数字,但如果用户输入"x",循环将结束。我没有太多,但是如果我运行这个程序并输入"x",它就会出错,因为它正在寻找的数据类型是双精度,所以它不能按照我想要的方式工作。除了我在这里拥有的方式之外,有没有另一种方法可以使循环结束而不是程序出错?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//function

//main function
int main()
{
//variables
double n1, n2;
//input
do {
cout << "Enter the first number n";
cin >> n1;
cout << "Enter the second number n";
cin >> n2;
//output
} while (true);

return 0;
}

您可以将n1n2x(字符串(进行比较。如果其中一个等于x则终止循环。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
//function

//main function
int main()
{
//variables
string n1, n2;
double n3, n4;
//input
do {
cout << "Enter the first number n";
cin >> n1;
cout << "Enter the second number n";
cin >> n2;
if(n1 == "x" || n2  == "x"){ //  n1 or n2 with "x" .
break;
}
n3 = stod(n1); // string to double.
n4 = stod(n2);

//output
} while (true);

return 0;
}

让输入值是字符串,然后将它们转换为 char 数组,然后您可以检查数组中的第一个元素是否是 x,如果是,则中断。然后,您可以在将其转换为双精度后执行任何需要执行的操作。

string n1, n2;
do {
cout << "Enter the first number n";
cin >> n1;
cout << "Enter the second number n";
cin >> n2;
char[] n1Array = n1.toCharArray();
if (n1[0] == 'x') break;
char[] n2Array = n2.toCharArray();
n1Double = atof(n1Array);
n2Double = atof(n2Array);
//output
} while (true);

我认为应该这样做。