Итак, я пытаюсь заставить этот C-код работать. Он компилирует, но производит неправильные выходы. Он должен перечислить все квадратные числа pefect между 1 и выбранным значением. Он делает что-то неправильно, и после многих проб и ошибок я думаю, что проблема связана с работой модуля ... как его усечение рано или что-то другое странное.C Код Для цикла с вложенными If; модулем и sqrt проблемой
// 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*/
}
Выход на codepad является:
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_int как int снова. – Jon
право, предназначено только для написания 1, 4 и 9. Спасибо. – Miloki