【发布时间】: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;