如何第一次写出正确的代码?

发布于 2024-08-13 14:12:29 字数 2545 浏览 3 评论 0原文

在第一次尝试完成一些编程任务时,我通常会犯很多错误(逻辑错误、语法错误)。我必须编写单元测试来检测这些错误。当我接受采访时,这一点尤其成问题。在这种情况下,我面临压力,无法使用编译器和单元测试来测试我的代码。

我的问题是首先如何编写正确的代码?我知道这很困难。有没有什么务实的方法可以在第一时间减少bug?

我被要求编写一个函数来接收指向 int 数组的指针和数组的大小。用素数填充该数组。这根本不是一个困难的问题。但我第一次犯了很多错误,并且不断发现新的错误。由于这是一次电话采访,我被要求输入答案并将其发送给思想邮件。

我的第一次尝试

    void prim(int * array, int size) 
{ bool isPrime = true; 
for (int i=0;i<size;i++) 
{  
for (int j = 2;j<i/2;j++)  
{    if (i%j==0){
        isPrime = ture;
        *array = i;
        array++;

      }  } } }

在 gmail 中编写代码是一个非常糟糕的主意。我再也不会这么做了。我知道该程序需要两个 for 循环。然而,代码中存在一些大问题

  1. “i”不应在第一个循环结束时增加。
  2. 如果 i%j==0,isPrime 应该为 false,
  3. 当我们找到素数时,数组操作应该放在循环的末尾。

我的第二次尝试,我添加了 isPrime 测试,修复了一些错误并重新提交。

    void prim(int * array, int size)
    {
    bool isPrime = true;

    for (int i=0;i<size;i++)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)

{
    *array = i;
    array++;
}
 }
}

代码中仍然存在一些根本性错误。但我的时间到了,我尝试在第三次尝试中修复它们。

  void prime(int * array, int size)
    {

   assert(array != null)
   assert(size>0)

    bool isPrime = true;

    for (int i=0;i<size;)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)
{
    *array = i;
    array++;
   i++;
}
 }
}

最后。面试结束后,我感觉自己真的充实了。我将代码复制到 IDE 中,修复了所有错误并进行了测试。我把这个发给我的面试官并对此表示抱歉。我真的很惊讶我竟然在这么小的问题上犯了这么多错误。 最终版本

#include <iostream>
#include <assert.h>
using namespace std;


void prime(int * array, int size)
{

    assert(array != 0);
    assert(size>0);
    if (size == 1){
        *array=2;
        return;
    }
    else {
        *array=2;
        array++;
    }
    bool isPrime = true;
    int testNum = 3;
    for (int i=1;i<size;)
    {
        isPrime = true;
        for (int j = 2;j<testNum;j++)
        {
            if (testNum%j==0){
                isPrime = false;
                break;
            }

        }
        if (isPrime)
        {
            *array = testNum;
            array++;
            i++;
        }
        testNum++;
    }
}
    int _tmain(int argc, _TCHAR* argv[])
    {
        int t[5]={0,};
        int sample[5]={2,3,5,7,11};
        prime(t,5);
        for (int i=0;i<5;i++){
            assert(t[i]==sample[i]);
        }
        return 0;
    }

I usually make lots of mistakes (logic errors, syntax errors) in the first attempt to accomplish some programming tasks. I have to write unit test to detect those bugs. This is especially problematic when I am in an interview. In that situation, I am under pressure and I can not test my code with compiler and unit test.

My question is that how can I write correct code in the first place? I know it is difficult. Is there any pragmatic approach to reduce bugs at the first time?

I was required to write a function that receives a pointer to an int array and the size of the array. Fill that array with prime number. It's not a difficult problem at all. But I made lots of mistakes at the first time and keep finding out new bugs. Since it was a phone interview I was asked to type the answer and send it thought mail.

My first try

    void prim(int * array, int size) 
{ bool isPrime = true; 
for (int i=0;i<size;i++) 
{  
for (int j = 2;j<i/2;j++)  
{    if (i%j==0){
        isPrime = ture;
        *array = i;
        array++;

      }  } } }

It was a really bad idea to write code in gmail. I will never do it again. I knew the program needs two for loops. However there are some big problems in the code

  1. 'i' should not increase at the end of first loop.
  2. if i%j==0, isPrime should be false
  3. the array operation should be put at the end of loop when we find a prime

My second try, I added isPrime test, fixed some errors and resubmitted it.

    void prim(int * array, int size)
    {
    bool isPrime = true;

    for (int i=0;i<size;i++)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)

{
    *array = i;
    array++;
}
 }
}

There are still some fundamental errors in the code. But my time is up, I try to fix them in my third try.

  void prime(int * array, int size)
    {

   assert(array != null)
   assert(size>0)

    bool isPrime = true;

    for (int i=0;i<size;)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)
{
    *array = i;
    array++;
   i++;
}
 }
}

Finally. After the interview, I felt that I really massed up. I copied the code into my IDE, fixed all the bugs and tested it. I sent this to my interviewer and said sorry about that. I was really surprised by how many errors I could make in such a small problem.
Final Version

#include <iostream>
#include <assert.h>
using namespace std;


void prime(int * array, int size)
{

    assert(array != 0);
    assert(size>0);
    if (size == 1){
        *array=2;
        return;
    }
    else {
        *array=2;
        array++;
    }
    bool isPrime = true;
    int testNum = 3;
    for (int i=1;i<size;)
    {
        isPrime = true;
        for (int j = 2;j<testNum;j++)
        {
            if (testNum%j==0){
                isPrime = false;
                break;
            }

        }
        if (isPrime)
        {
            *array = testNum;
            array++;
            i++;
        }
        testNum++;
    }
}
    int _tmain(int argc, _TCHAR* argv[])
    {
        int t[5]={0,};
        int sample[5]={2,3,5,7,11};
        prime(t,5);
        for (int i=0;i<5;i++){
            assert(t[i]==sample[i]);
        }
        return 0;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

夜声 2024-08-20 14:12:29

大量练习:)

尽管我不认为一些小的语法错误会给面试官带来太多困扰——只要你的理论是合理的。

lots of practice :)

although i dont think a few minor syntax errors will bother an interviewer too much - as long as your theory is sound.

っ左 2024-08-20 14:12:29

你不会喜欢这个答案,那就是:当一名程序员 20 年。

You won't like the answer, which is: be a programmer for 20 years.

埖埖迣鎅 2024-08-20 14:12:29

先写评论吧。
编写注释将帮助您指定代码的主要目标,并且在以后您的代码需要修改时也会有所帮助。
至于面试,它也将帮助面试官更好地理解你所写的想法,即使你的代码有点错误。

Write comments first.
Writing comments will help you specify the main objective of your code and will help later, if your code needs revision in the future.
As for the interview, it will also help interviewer better understand the idea you are writing even if your code is a little bit buggy.

姐不稀罕 2024-08-20 14:12:29

您似乎在问两个问题:

  • 我如何在面试中回答编码问题?
  • 如何编写干净的良好代码?

回答第一个问题比第二个问题更容易。请注意,如果您不告诉面试官可能存在的问题,他们可能会认为您没有意识到存在错误,并且您不知道如何纠正它们。这里有一些建议,

  • 告诉面试官,你预计第一次剪辑时可能会出现语法错误,
  • 用文字描述你的算法,
  • 先写伪代码,先
  • 写函数,自上而下地
  • 与面试官讨论解决问题的方法,
  • 告诉面试官你如何纠正错误

。第二个问题,练习。实践。写很多代码。是的,测试驱动开发是一个非常好的主意。

You seem to be asking two questions

  • How do I answer coding questions at interviews?
  • How do I write good clean code?

Answering the first question is easier than the second. Please note that if you don't tell the interviewers about possible problems they're likely to presume that you don't realize there are errors, and you won't know to correct them. Here are some suggestions

  • tell the interviewer that you expect there may be syntax errors on your first cut
  • describe your algorithm in words
  • write pseudo code first
  • write functions top down
  • talk your way through the problem with the interviewer
  • tell the interviewer how you correct the errors

As for the second question, practice. Practice. Write lots of code. And yes, test driven development is a very good idea.

昨迟人 2024-08-20 14:12:29

我会告诉你什么对我有效。即时错误检测器插件将为您提供很大帮助。

我用Resharper。在使用它之前,我在编译时遇到了太多错误。

两周前,我不得不使用一个干净的视觉工作室(未安装 resharper),并且我编译了源代码,几乎没有错误。

有人说这个工具让程序员变得懒惰,但我不同意。

I will tell you what works on me. An on-the-fly error detector addon will help you very much.

I use Resharper. Before using it i had too many error at compilation time.

2 weeks ago i had to use a clean visual studio (resharper not installed) and I compiled the source with almost no errors.

Some people say that this tool makes programmer lazy, but i don't agree.

胡大本事 2024-08-20 14:12:29

您需要简单地编写很多程序,从非常基本的程序开始,然后是更复杂的程序。

同样在我上大学的第一年,当我们介绍 Pascal 和 C 编程时,我们必须一直在纸上“编码”。起初我发现它很愚蠢,现在我记得所有的错误(构建测试是为了让它们包含所有最常见的错误,比如 if(x = y) 等),所以我最近开始用 Java 在纸上编码(尽管我'我还是一个java初学者)。

现在我编写各种各样的代码(每当我找到一个不错的想法时,我就会编写它),我认为这是改进的唯一方法。

You need to simply program A LOT, start with really basic programs, then more complex ones.

Also during my first years at the uni, when we had introduction to programming in Pascal and C we had to "code" on paper all the time. At first I found it stupid, now I remember all the mistakes (tests were constructed so they would contain all the most common mistakes, like if(x = y) etc.) so I started coding on paper in Java recently (though I'm still a java beginner).

Now I code all sorts of things (whenever I find a decent idea I code it) and I think it's the only way to improve.

一花一树开 2024-08-20 14:12:29

首先如何编写正确的代码

如果这个问题有一个微不足道的答案,我们就不会有日常工作。

虽然有一些关于软件程序“可证明性”的学术工作,但逻辑思维和对细节的关注是无可替代的——特别是如果你只有一块白板和一支记号笔的话。

正如其他人提到的,面试官通常会对语法错误给予一定的余地,但严重的逻辑错误不太可能被忽视。

how can I write correct code in the first place

If this question had a trivial answer, we wouldn't have day jobs.

While there is some academic work on the "proveability" of software programs, there's no substitute for a logical thinking and attention to detail -- particularly if all you have is a whiteboard and a marker.

As others have mentioned interviewers generally give some leeway for syntax errors but gross logical mistakes are less likely to be ignored.

旧时浪漫 2024-08-20 14:12:29

慢即平滑,平滑即快

<前><代码> - 未知

花点时间思考一下代码。当你工作/练习时,你会犯更少的错误,并且你的编码速度会更快。就像其他事情一样,当你急于做某事并且不认为自己会犯错误时。你做的事情越多,它就越成为一种反应而不是一个想法。

Slow is smooth, Smooth is fast

                   - Unknown

Take your time and think about the code. As you work/practice you will make less mistakes and you will get faster in your coding. Just like anything else when you rush to do something and don't think you make mistakes. The more you do that thing the more it becomes a reaction instead of a thought.

雨的味道风的声音 2024-08-20 14:12:29

实践。如果您通常在工作或学校使用 IDE,请每隔一周花一天时间在不使用 IDE 的情况下进行编码。

如果你能举出你容易犯的错误类型的例子,人们可能会给出更具体的建议。

Practice. If you usually use an IDE at work or at school, spend one day every other week coding without it.

If you can give an example of the types of errors you're prone to, folks can probably give much more specific advice.

围归者 2024-08-20 14:12:29

练习,使用适合工作的正确工具,编写大量代码,学习你的工具,编写更多代码,阅读有关编程的书籍,编写更多代码。你明白了。编程是一项艰苦的工作,没有什么捷径。

也就是说,任何在面试中给出编码任务并期望得到可以干净编译并开箱即用的结果的人显然是疯狂的,你不想在那里工作。优秀的管理者使用编码任务来了解你如何解决问题。

Practise, use the right tools for the job, write lots of code, learn your tools, write more code, read books about programming, write even more code. You get the idea. Programming is hard work, and there aren't really any shortcuts.

That said, anybody giving a coding task at an interview expecting a result which will compiles cleanly and works out-of-the box is clearly mad, and you do not want to work there. Good managers use coding tasks to see how you approach a problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文