是否可以忽略 "scanf_s" 中的某些字符?
Is it possible to ignore certain characters in "scanf_s"?
这是我的代码。这是一项学校作业。我必须编写一个程序来使用巴比伦人开发的方法等来计算数字的平方根,这不是重要的部分。我想知道的是,是否可以忽略我的 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);
}
Scanf
读取终端输入的任何内容(字符或整数)
您可以做的一种方法是检查 scanf
的 return 语句读取的输入是否为整数。
这里是示例代码
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?
这是我的代码。这是一项学校作业。我必须编写一个程序来使用巴比伦人开发的方法等来计算数字的平方根,这不是重要的部分。我想知道的是,是否可以忽略我的 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);
}
Scanf
读取终端输入的任何内容(字符或整数)
您可以做的一种方法是检查 scanf
的 return 语句读取的输入是否为整数。
这里是示例代码
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?