简体   繁体   English

用C ++查找数字

[英]finding numbers with C++

I have a problem in writing a program with C++. 我在用C ++编写程序时遇到问题。 I have been studying C# and Java but C++ is a way different to me, so I need your help. 我一直在学习C#和Java,但是C ++与我不同,所以我需要您的帮助。

My task is to make program which: reads an input from a text box than returns the nubers from that input which has two digits and their sum is 9. 我的任务是制作一个程序:从文本框中读取输入,然后从该输入返回包含两个数字且其总和为9的数字。

For example: 例如:

Input: 12 231 81 53 522 11 63 输入:12 231 81 53 522 11 63

Output: 81 63 输出:81 63

I need it a ssimple as possible so I could understand it. 我需要它尽可能简单,这样我才能理解。 Thank you in advance. 先感谢您。

As you know C# and Java, how would you solve this problem in C# or Java? 如您所知C#和Java,您将如何用C#或Java解决此问题? Start with that, and then you can modify that solution to fit with C++, the algorithm should be the same, and the syntax is more similar than you may think. 首先,然后您可以修改该解决方案以适合C ++,算法应该相同,并且语法比您想象的更相似。

For instance, start with the following and implement the OutputResult function: 例如,从以下内容开始并实现OutputResult函数:

class Test
{
    static void OutputResult(String contentsToParse)
    {
        // TODO: Implementation here.
    }

    static void Main()
    {
        String contentsOfTextBox = "12 231 81 53 522 11 63";
        OutputResult(contentsOfTextBox);
    }
}

This looks like a question about C++ operators. 这看起来像一个关于C ++运算符的问题。

  • To read the integers from a string you could use the istringstream input operator: >> 要从字符串读取整数,可以使用istringstream输入运算符: >>
  • To test if an integer has two digits you could use the built-in greater than > and less than < operators with the boolean and && operator. 要测试整数是否具有两位数,可以将内置的大于>和小于<运算符与布尔值&&&运算符一起使用。
  • To separate the two digits you could use the built-in integer division / and modulus % operators. 要分隔两位数,可以使用内置的整数除/和模数运算符。
  • To check the sum of the digits you could use the built-in addition + and equality == operators. 要检查数字的总和,可以使用内置的加法+和等于==运算符。

Read each character individually, one by one. 逐个阅读每个字符。

If it's a digit (>= '0' && <= '9'), add one to the "read digits" counter and convert it to a number. 如果是数字(> ='0'&& <='9'),请在“ read digits”计数器上加1,然后将其转换为数字。 If not, reset the "read digits" counter and continue to parse until you hit the end. 如果不是,请重置“已读数字”计数器并继续解析,直到结束为止。

If you reset the counter when it has exactly two read digits, check if those two numbers add up to 9 and print them out in case they do. 如果在正好有两个读取数字的情况下重置计数器,请检查这两个数字是否总计为9,​​并打印出来以防万一。

Since you never need to store more than two numbers, you can have a static array that can hold these two digits. 由于您永远不需要存储两个以上的数字,因此可以拥有一个可以容纳这两个数字的静态数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM