我需要我的程序说“这个值是无效的” [英] I need my program to say "this value is not valid"
问题描述
这是我的工作问题。
三角形数字序列是通过添加自然数生成的。因此,第7个三角形数字将是 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
。前十个术语是: 1,3,6,10,15,21,28,36,45,55,...
The sequence of triangle numbers is generated by adding the natural numbers. Hence, the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
让我们列出前七个三角形数字的因子:
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
我们可以看到,28是第一个三角形数字超过五个除数。第一个三角形数字的值超过一百个除数是什么?
We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over one hundred divisors?
这是我的代码。我有错误处理的麻烦。唯一有效的输入是数字。如果我输入一个数字以外的任何东西,我想让它响应错误或类似的东西。
and this this is my code. I am having trouble with the error handling.The only valid inputs are numbers. If I enter anything other than a number, i want it to respond "ERROR" or something like that.
int main()
{
int div=0,sum=0,num,i=1,count=0,a;
cout<<"Enter the number of divisors"<< endl;
cin>>a;
while(div<=a) {
div=0;
sum=sum+i;
for(int j=1;j<=sum;j++)
if (sum%j==0)
div++;
chk++;
i++;
}
cout<<"Value of first triangle number is "<<sum<<endl;
cout<<"Value of triangle number is "<<count<<endl;
return 0;
}
我的程序在我的伪代码和流程图之前,所以如果any1可以帮助我通过我的伪码n流程图,这将是值得赞赏的。 =)
also i did my program before my pseudocode and the flowchart,so if any1 can help me guide through my pseudocode n flowchart,it would be appreciated.thank you. =)
推荐答案
检查输入和转换是否成功的最简单的方法是检查流是否仍然良好: / p>
The simplest way to check whether the input and conversion succeeded is to check that the stream is still good afterwards:
if (std::cin >> a) {
// Success
} else {
// Failure
}
如果要恢复,那么您将需要清除流的状态,并且还要删除错误的输入,然后重试;例如
If you want to recover and try again, then you will need to clear the stream's status, and also remove the bad input, before retrying; something like
std::cin.clear();
std::cin.ignore(unsigned(-1), '\n');
这篇关于我需要我的程序说“这个值是无效的”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!