gpt4 book ai didi

c - 是否可以忽略 "scanf_s"中的某些字符?

转载 作者:行者123 更新时间:2023-11-30 20:22:02 27 4
gpt4 key购买 nike

这是我的代码。这是学校作业。我必须编写一个程序来使用巴比伦人开发的方法等来计算数字的平方根,这不是重要的部分。我想知道是否可以忽略 scanf 中的字母,这样当我输入字母时,它就不会在我的终端中变得狂暴。欢迎并非常感谢任何帮助。

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

double root_Approach(double s); // defines the two functions
void ask_Number(void);

int main() {

ask_Number(); // calls function ask_Number

printf("\n\n");
system("pause");
return 0;
}

double root_Approach(double s) {

double approach;
approach = s;
printf("%.2lf\n", s); // prints initial value of the number

while (approach != sqrt(s)) { // keeps doing iteration of this algorithm until the root is deterimened

approach = (approach + (s / approach)) * 0.5;

printf("%lf\n", approach);
}

printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes

return approach;
}

void ask_Number(void) {

double number;

while (1) {
printf("Input a number greater than or equal to 0: "); // asks for a number
scanf_s("%lf", &number); // scans a number

if (number < 0) {
printf("That number was less than 0!!!!!!\n");
}
else {
break;
}
}
root_Approach(number);
}

最佳答案

  1. Scanf 读取来自终端的任何输入(字符或整数)

一种方法是检查 scanf 的返回语句读取的输入是否为整数。

这是示例代码

    int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");

`

this link may be helpful Check if a value from scanf is a number?

关于c - 是否可以忽略 "scanf_s"中的某些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com