由于没有明显的原因,简单的C程序无法工作

时间:2015-06-01 09:13:48

标签: c printf scanf

我想询问以下C代码,它不起作用,我不明白为什么。它没有输入if语句,但是当我使用cin和cout而不是printf / scanf在C ++中编译它时它工作得很好。

#include "stdafx.h"
#include <conio.h>

int sqrt(int x)
{
    if(x < 0) 
    {
        return printf("no negative numbers");
        return 0;
    } 
    else if(x == 0 || x == 1) 
    {
        return x;
    } 
    else
    {
        int lowerbound = 1, upperbound = x;
        int root = lowerbound + (upperbound - lowerbound)/2;

        while(root > x/root || root+1 <= x/(root+1))
        {
            if(root > x/root)
            {
                upperbound = root;
            } 
            else
            {
                lowerbound = root;
            }
            root = lowerbound + (upperbound - lowerbound)/2;
        }

        if(root*root==x)
        {
            return root;
        }
        else
        {
            return -1;
        }
    }
}

void main()
{
    int i = 0;
    int start = 0;
    int end = 0;

    printf("start and an end:  ");
    scanf_s("%d%d", &start, &end);

    for (i = start; i < end; i++);
    {
        if(sqrt(i)>=0)
        {
            printf("%d",i);
            printf("---");
        }
    }

    return;
}

2 个答案:

答案 0 :(得分:2)

  1. 您需要#include <stdio.h>才能使用printf()scanf_s()
  2. for循环错误。 for(i = start; i < end; i++); 所以,

      if(sqrt(i)>=0)
      {
         printf("%d",i);
         printf("---");
      }
    

    只会执行一次而不是end-1次,如果您期望的话。移除;

  3. 之后的for()
  4. main函数声明为void main(),最后它会执行return。编译器必须在这里发出警告。将其更改为int main()return 某些,这是有效的int

答案 1 :(得分:2)

错误在此行

 for (i = start; i < end; i++);
                              ^   // remove `;` semicolon
相关问题