在這個程式中,我試圖用牛頓方程1/2(x a/x) 僅使用整數來計算平方根。所以如果我重復這個方程至少 10 次,它應該將數字除以 1000 并給出 a/1000 的平方根的近似值。這是代碼:
int main (){
int32_t a, x; //integers a and x
float root;
do{
scanf ("%d", &a); // get value of a from the user
if (a < 1000 ){ // if chosen number is less than 1000 the programm ends.
break;
}
x = ((float) a / 1000); //starting value of x is a / 1000;
for (int i = 0; i < 50;i )
{
root = ((float) x * (float) x a/1000) / ((float)2*x); // convert int to float //through casting
x = (float)root; // refresh the value of x to be the root of the last value.
}
printf ("%f\n", (float)root);
}while (1);
return 0;
}
所以如果我計算 2000 的平方根,它應該回傳 2(1.414..) 的平方根,但它只是給出一個近似值:1.50000 我如何使用整數糾正這個并用浮點數轉換它們?謝謝
uj5u.com熱心網友回復:
x = (x a / x) / 2fora = 2000000和x0 = 1000(所有整數變數)的迭代是1500,1416和1414。然后200000000給予14142等等。
uj5u.com熱心網友回復:
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char * *argv, char * *envp) {
int32_t a, x; //integers a and x
float root;
do {
scanf ("%d", &a); // get value of a from the user
if (a < 1000) { // if chosen number is less than 1000 the program ends.
break;
}
x = (int32_t)((float) a / 1000.0f); //starting value of x is a / 1000;
for (int i = 0; i < 1000; i ) {
// Fixed formula based on (x a/x)/2
root = ((float)x (((float)a) / (float)x)) / 2.0f;
//Below, wrong old formula
//root = ((float) x * (float) x a / 1000) / ((float) 2 * x); // convert int to float //through casting
x = (int32_t) root; // refresh the value of x to be the root of the last value.
}
printf ("%f\n", root);
} while (1);
return (EXIT_SUCCESS);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335261.html
上一篇:如何解決一個模式?
下一篇:將整數中的每個數字存盤在陣列中
