Using division to judge the number of digits BUG is here again

Error 1 (entered into an infinite loop) ↓

#pragma warning(disable:4996)//为了防止scanf()函数因为没有返回值而报错
#include<stdio.h>

//用除余法:判断数字为几位数
int main() {
    
    
	long long n;
	int a,i=1;

	printf("请输入一个数字:\n");
	scanf("%d", &n);

	a = n / 10;

	for(i = 1; a < 1; i++){
    
    	//这里应改为 a>1, for循环条件句为真时才执行循环体
		a = n / 10;	//这里应该改为a=a/10
	}

	printf("n是%d位数", i);

	return 0;

}

Correct 3
An error was reported at the beginning,
(Later, no error was reported after recompiling with release and debug) ↓

#pragma warning(disable:4996)//为了防止scanf()函数因为没有返回值而报错
#include <stdio.h>

//用除余法:判断数字为几位数
int main() {
    
    

	long long n;
	long long  i=1;
	int a;

	printf("请输入一个数字:\n");
	scanf("%d", &n);

	a = n / 10;

	for (i = 1; a > 0; i++) {
    
    
		a = a / 10;
	}
	
	printf("n是 %lld 位数", i);

	return 0;
}

Correct 1↓

#pragma warning(disable:4996)//为了防止scanf()函数因为没有返回值而报错
#include<stdio.h> 
int main() {
    
    

	long long n;
	long long  i=1;
	int a;
	
	printf("请输入一个数字:\n");
	scanf("%d", &n);
	
	a = n / 10;
	
	for (i = 1; a > 0; i++) {
    
    
		a = a/ 10;
	}
	printf("n是 %lld 位数", i);

	return 0;
}

Correct 2↓

#pragma warning(disable:4996)//为了防止scanf()函数因为没有返回值而报错
#include <stdio.h>

//用除余法:判断数字为几位数
int main() {
    
    

	int n;
	int  i=1;
	int a;

	printf("请输入一个数字:\n");
	scanf("%d", &n);

	a = n / 10;

	for (i = 1; a > 0; i++) {
    
    
		a = a / 10;
	}

	printf("n是 %d 位数", i);

	return 0;
}

The key question is actually here:

Insert picture description here
In this for loop, the value of n has not changed, so a has not changed, and it becomes an infinite loop, so it is wrong.

postscript

When you run the Console program in VS2019, the divided debug and release,
in which the debug process will generate a lot of documents, and have hidden I do not know what is running in the background,
while the release is the direct publisher, not so much the process of documents,
each There are advantages and disadvantages.

In my practice these days, there will be unexplained problems after using debug to run the program many times, but the correct program will not run, so we should pay more attention to this in the future. Sometimes it is not the program error, but the problem of the compiler itself. , This is really annoying, so I have the opportunity to study it in the future.

Information: In-
depth understanding of the difference between Debug and Release

Guess you like

Origin blog.csdn.net/weixin_42417585/article/details/105126760