【问题标题】:Simple C program not working because of no obvious reason [closed]简单的 C 程序由于没有明显的原因而无法工作[关闭]
【发布时间】:2015-06-01 09:13:48
【问题描述】:

我想询问以下 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;
}

【问题讨论】:

  • 您应该澄清“不工作”的含义 - 编译错误、运行时错误等。
  • if语句中没有代码输入怎么办?
  • return printf("no negative numbers"); return 0; --> fprintf(stderr, "no negative numbers"); return -1;

标签: c printf scanf


【解决方案1】:

错误在这一行

 for (i = start; i < end; i++);
                              ^   // remove `;` semicolon

【讨论】:

    【解决方案2】:
    1. 您需要#include &lt;stdio.h&gt; 才能使用printf() 和scanf_s()
    2. 你for 循环是错误的。 for(i = start; i &lt; end; i++); 所以,

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

      只会执行一次,而不是end-1 次,如果您期望的话。删除for()之后的;

    3. main 函数被声明为void main(),最后它执行return。编译器必须在此处抛出警告。将其更改为int main() 和return something 这是一个有效的int。

    【讨论】:

    • 当我包含它时没有任何变化。程序在输入''start''和''end''后停止
    猜你喜欢
    • 2020-11-18
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多