C错误:应为指针

C错误:应为指针,c,C,我用C语言编写了一个简单的程序,可以找出一个数是否为素数。我是C语言的新手,决定尝试使用scanf而不是硬编码的数字来检查。当我运行代码时: #include <stdio.h> typedef int bool; #define true 1 #define false 0 int main(){ //I am going to check if the "checking" variable is a prime int checking; scanf("%d",c

我用C语言编写了一个简单的程序,可以找出一个数是否为素数。我是C语言的新手,决定尝试使用scanf而不是硬编码的数字来检查。当我运行代码时:

#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main(){
  //I am going to check if the "checking" variable is a prime
  int checking;

  scanf("%d",checking);

  //"stopper" is where the for loop will stop
  int stopper = checking**0.5 + 1;

  //"found" will show if I have found something bad
  bool found = false;

  for (int i = 2; i < stopper; i++)
  {
    if (checking % i == 0){found = true; break;}
  }

  if (!found) {printf("it is prime");}
  else {printf("it is not prime");}

}
我不知道怎么解决这个问题

编辑:我刚做了stopper=checking/2,程序崩溃了

int stopper=检查**0.5+1

第12行。。。您希望
**
操作员做什么?
*
通常执行乘法或取消对指针的引用。 编译器可能会对其进行如下解释:

int stopper = checking * (*0.5) + 1;
当然,尝试取消对浮点(
*0.5
)的引用是错误的/不可能的,因此会出现错误

你是说:

  • 您不是指
    **
    ,而是指
    *
    (乘法)
  • 您指的不是
    **
    (不是C运算符),而是
    pow()
    (提升到的幂)
你还需要明确——即使你是这方面的专家,读者也可能不是,你很可能是错的

如果您不确定发生了什么,请使用大括号来说明具体情况,您指的是以下哪项

  • int stopper=检查*(0.5+1)
  • int-stopper=(检查*0.5)+1
  • int-stopper=pow(检查,0.5)+1
  • int-stopper=pow(检查,0.5+1)
如果你真的在寻找平方根,那么正如@JeremyP所说的,颠倒你的想法-乘法比
pow()要便宜得多。


for(int i=2;i*i您的程序中有两个问题:

(1) 更换

int stopper=正在检查**0.5+1;

int stopper=检查*0.5+1;

(2) 更换

scanf(“%d”,正在检查);

scanf(“%d”,&checking);


在这些修正之后,您应该很好地进行调整。

没有内置的运算符将一个数字提升为另一个数字的幂。有一个函数可以做到这一点——还有一个平方根函数,但您不需要它们(见下文)

被解析为

x* (*y)
这就是指针错误的来源

不要试图找到平方根,而是从另一个方向开始,像这样改变for循环

for (int i = 2; i * i <= checking; i++)

首先,
scanf
是错误的。 使用
scanf(“%d”,&checking);

要查找平方根,请使用
sqrt
函数的
math.h

int stopper = sqrt(checking) + 1;
您的代码中有很多键入错误。请在提问之前更正您的语法


typedef int bool;
为什么不使用
stdbool.h
scanf(“%d”,正在检查);
-->
scanf(“%d”,正在检查)
我不知道如何解决这个问题。
检测到家庭作业倾倒态度。请在询问之前做基础研究。你的意思是
int stopper=checking*0.5+1;
而不是
int stopper=checking**0.5+1;
?@hexidian你的代码中有很多错误。
scanf
输入错误。
int stoper=检查**0.5+1;
是错误的。你不能有双重乘法。
if!found
括号不存在。请更正你的语法。这些只是基本问题,一旦你学会了语法就会解决。不,
**
他指的是“提升到.他试图得到
检查的平方根
噢,哇。那是python的,不是C的。抱歉这个愚蠢的问题,我是个白痴
x* (*y)
for (int i = 2; i * i <= checking; i++)
scanf("%d",&checking);
//         ^- scanf needs a pointer to an int.
int stopper = sqrt(checking) + 1;