【问题标题】:C Code For loop with nested If; modulus and sqrt issue带有嵌套 If 的 C 代码 For 循环;模数和 sqrt 问题
【发布时间】:2015-03-26 16:19:08
【问题描述】:

所以,我正试图让这个 C 代码工作。它编译,但产生不正确的输出。它应该列出 1 和所选值之间的所有完美平方数。 它做错了,经过大量试验和错误后,我认为问题出在模数运算上……就像它提前截断或做一些其他奇怪的事情一样。

// C Code


/*This program will identify all square numbers between one and a chosen integer*/

#include <stdio.h>
#include <math.h>

int main(){

int i, upper, square_int;
float square;
printf("This program will identify all square numbers between one and a chosen integer");

printf("Please enter the upper limit integer:");
scanf("%d", &upper);

upper = 13; /*scanf is the primary integer input method; this is here just to test it on codepad*/

for (i = 1; i<= upper; ++i) /*i want to run through all integers between 1 and the value of upper*/
{ 
    square = sqrt(i);  /* calc square root for each value of i */
    square_int = square;  /* change the root from float to int type*/

    if (i % (int)square_int == 0) /*check if i divided by root leaves no remainder*/
        printf("%d\n", i);  /*print 'em*/
}
printf("This completes the list of perfect squares between 1 and %d",upper);

return 0; /*End program*/
}

键盘上的输出是:

This program will identify all square numbers between one and a chosen integerPlease enter the upper limit integer:1
2
3
4
6
8
9
12
This completes the list of perfect squares between 1 and 13

这当然是错误的。我希望得到 1、2、4 和 9 回来。谁能指出我在这里搞砸了?

【问题讨论】:

  • “我希望得到 1、2、4 和 9” -> 2 不是完美的正方形。
  • square_int=square 演员正在搞乱您的算法概念。我想你知道这很狡猾,因为你稍后会再次将 square_int 转换为 int。
  • 对,就是写 1、4 和 9。谢谢。
  • 如果你不明白发生了什么,为什么不打印所有的值进行调试。 (与printf。)那么你必须看看有什么不符合你的预期。

标签: c if-statement nested-loops modulus sqrt


【解决方案1】:

这是一个更简单的算法

int i = 1;
while (i*i < upper)
{
    printf("%d\n", i*i);
    ++i;
}

另一种方法是计算平方根,将其转换为 int,然后比较数字。

for (i = 1; i <= upper; ++i)
{
    square = sqrt(i);
    square_int = square;
    if (square == (float)square_int)
        printf("%d\n", i );
}

【讨论】:

  • 我不完全明白为什么要在两者之间使用浮点变量。为什么不直接使用int sqroot = sqrt(i);,因为sqrt(3) 返回一个double,它将转换为int 以存储在sqroot 变量中。
  • @luis 因为在这个算法中,我将浮点数(或双精度数)与整数进行比较。我们也可以对 int 进行平方,看看它是否等于 i。这将是另一种算法。
【解决方案2】:

您的模运算不正确。在i = 6 的情况下,square_int 将变为2,因此i % (int)square_int 等于6 % 2,从而导致0

您可以改为检查 square_int * square_int == i

【讨论】:

  • 谢谢大家。正在测试和实现来自 chmike 的代码,并没有注意到额外的帖子。它现在可以工作了,它吐出的正是我想要的。
  • 顺便说一句,我不知道我到底要去哪里模数...在我的早会中做了一些涂鸦笔记,然后立即开始编写代码。当您跳过数据测试阶段时会发生这种情况...谢谢你们今天把我从地板上接过来。
【解决方案3】:

你说你期望得到1, 2, 4, 9,这意味着你不期望得到3

让我们看看i == 3

sqrt(3) == 1.732051

(int) 1.732051 == 1

3 % 1 == 0.

这意味着它实际上做了它应该做的事情,但它不会检查一个数字是否是一个正方形。

检查数字是否为正方形的简单算法是:

sqrt_int = sqrt(i) + 0.5;

if (square_int * square_int  == i)
    printf("%d\n", i);

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多