我想询问以下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;
}
答案 0 :(得分:2)
#include <stdio.h>
才能使用printf()
和scanf_s()
您for
循环错误。 for(i = start; i < end; i++);
所以,
if(sqrt(i)>=0)
{
printf("%d",i);
printf("---");
}
只会执行一次而不是end-1
次,如果您期望的话。移除;
for()
main
函数声明为void main()
,最后它会执行return
。编译器必须在这里发出警告。将其更改为int main()
和return
某些,这是有效的int
。
答案 1 :(得分:2)
错误在此行
for (i = start; i < end; i++);
^ // remove `;` semicolon