如何正确终止此循环?
How do I terminate this loop properly?
我正在尝试制作一个程序,它要求用户输入一个我最终将计算的数字,但如果用户输入"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;
}
您可以将n1
或n2
与x
(字符串(进行比较。如果其中一个等于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);
我认为应该这样做。
相关文章:
- while 循环不以哨兵值终止
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- C++ 即使不满足条件,循环也会终止
- 为什么 EOF 在循环扫描期间没有终止?
- 对于检查 >=0 终止条件时的循环索引类型
- 程序在终止循环后不接收输入
- 即使我尝试递减 t,While 循环也没有终止
- 如何修复不会在退出选择时终止的 do-while 循环
- 如何用字符终止整数输入循环?
- 读入变量时循环终止,'Range_error' on C++
- 当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
- 如何正确终止此循环?
- 多个查询的循环过早终止
- 循环终止不正确时
- c 在函数的循环终止时
- 而循环终止问题
- 当循环终止被覆盖时
- 循环终止条件错误的 cpp 向量
- C++作业(循环终止时)
- 是否定义有一个随机的循环终止条件?